Spread for WinForms可以将表格数据导出为Excel,这篇文章主要介绍在导出为Excel时,开发人员经常遇到的一些问题做相关解答,具体如下:
1.Excel导出行头和列头信息
问题描述:导出Excel 时,如何导出行头和列头到Excel。
问题解答:ExcelSaveFlags枚举用于获取或设置保存Excel的行为。
关键代码:
this.fpSpread1.SaveExcel(“test.xls”,FarPoint.Excel.ExcelSaveFlags.SaveBothCustomRowAndColumnHeaders);
2.Excel导出表格无法编辑问题
问题描述:Spread 导出 Excel后表单只可以查看,但是无法进行编辑。
问题解答:可以通过 SheetView下Protect属性用于获取或设置导出Excel后表单是否可以编辑。
关键代码:
private void AllowEdit()
{
//取消保护状态
this.fpSpread1.Sheets[0].Protect = false;
//保存excel
this.fpSpread1.SaveExcel("test.xls");
}
3.如何导出图片到Excel
问题描述:如何向Spread 中添加图片,并且导出到Excel 中。
问题解答:通过ImageCellType 添加图片到单元格后,使用SaveExcel保存为Excel即可。
关键代码:
private void AddImageToCell()
{
FarPoint.Win.Spread.CellType.ImageCellType icelltype = new FarPoint.Win.Spread.CellType.ImageCellType();
icelltype.Style = FarPoint.Win.RenderStyle.Stretch;
icelltype.TransparencyColor = Color.Black;
icelltype.TransparencyTolerance = 100;
fpSpread1.Sheets[0].Rows[0].CellType = icelltype;
System.Drawing.Image image = (System.Drawing.Image)Properties.Resources.ResourceManager.GetObject("Tulips");
System.IO.MemoryStream stream = new System.IO.MemoryStream();
byte[] bytes;
string str;
image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
stream.Seek(0, System.IO.SeekOrigin.Begin);
bytes = stream.GetBuffer();
str = System.Convert.ToBase64String(bytes);
fpSpread1.Sheets[0].Cells[0, 0].Value = image;
fpSpread1.Sheets[0].Cells[0, 0].Text = "test";
fpSpread1.Sheets[0].Protect = false;
this.fpSpread1.SaveExcel("test.xls");
}
4.Sort结果导出到excel中
问题描述:Spread表单进行了数据排序,把排序结果导出到Spread 中。
问题解答:请参考代码。
关键代码:
this.fpSpread1.Sheets[0].SortRange(0, 0, fpSpread1.Sheets[0].RowCount, fpSpread1.Sheets[0].ColumnCount, true, new FarPoint.Win.Spread.SortInfo[] { new FarPoint.Win.Spread.SortInfo(0, true) });
this.fpSpread1.SaveExcel("test.xls");
5.导出边框到Excel
问题描述:如何设置单元格的边框样式,使其可以导出到Excel。
问题解答:Spread提供LineBorder等类用于设置边框。
关键代码:
private void ExportLineBorder()
{
fpSpread1.ActiveSheet.Cells[4, 2].Value = "test";//客户名称
fpSpread1.BorderCollapse = FarPoint.Win.Spread.BorderCollapse.Collapse;//合并显示
fpSpread1.ActiveSheet.Cells[2, 1, 4, 2].Border = new FarPoint.Win.LineBorder(Color.Black, 1, true, true, true, true);
fpSpread1.ActiveSheet.Cells[2, 5, 4, 6].Border = new FarPoint.Win.LineBorder(Color.Black, 1, true, true, true, true);
this.fpSpread1.SaveExcel("test.xls");
}
6.打印时能否像excel一样将打印的内容的宽度缩在一页纸内
问题描述:Spread 中内容宽度超过了一页纸的宽度,能否在导出 Excel时使其内容宽度设置在一页内。
问题解答:Spread提供了 ZoomFactor属性用于获取或设置缩放比例。
关键代码:
private void ExportZoomToExcel()
{
this.fpSpread1.ZoomFactor = 0.5f;
this.fpSpread1.SaveExcel("test.xls");
}