1、用dataGridView控件创建表格
这个就直接上导出到Excel的效果图如下:
2、添加引用
Spire.XLS.dll文件、Spire.XLS.dll和Spire.License.dll
3、在代码中添加引用的命名空间
using Spire.Xls;
4、代码如下:
public void DaoChu(DataGridView x)
{
//创建一个EXCEL 引用Spire.XLS.dll文件和Spire.Pdf.dll(所需要的反射载入的DII代码还依赖其他的.dll文件)
Workbook WB = new Workbook();
//获取第一个Sheet ,进行操作,从0开始
Worksheet table = WB.Worksheets[0];
//删除工作表
WB.Worksheets.RemoveAt(1);
//设置表格的名称
table.Name = "test";
//读出数据
object[,] testVal = new object[x.RowCount , x.ColumnCount ];
//写入数组
for (int i = 0; i < x.RowCount ; i++)
{
for (int j = 0; j < x.ColumnCount ; j++)
{
testVal[i, j] = x.Rows[i].Cells[j].Value;
}
}
//输入数据
table.InsertArray(testVal, 1, 1);
if(table.FirstColumn<1)
{
MessageBox.Show("查无数据时无法输出!", "无法输出!", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
//合并单元格
table.Range["A1:B1"].Merge(); //Excel中的A1和B1表格合并(第一行的第一列和第二列)
//(起始行,起始列、终点行、终点列)
//位置(1,4)→(2,4)
table.Range[1, 4, 2, 4].Merge(); //Excel中第一行的第四列与第二行的第四列合并
//设置边框的样式
CellRange CR = table.Range[table.FirstRow, table.FirstColumn, table.LastRow, table.LastColumn]; //第一行
CR.Borders.LineStyle = LineStyleType.Thin; //线的样式类型 口中×
CR.Borders[BordersLineType.DiagonalDown].LineStyle = LineStyleType.None;
CR.Borders[BordersLineType.DiagonalUp].LineStyle = LineStyleType.None;
CR.Borders.Color = Color.Black;
for (int C = table.FirstColumn; C <table.LastColumn ; C++)
{
table.AutoFitColumn(C);
}
//设置行高
for (int R = table.FirstRow; R < table.LastRow+1; R++)
{
table.Rows[R-1].RowHeight = 30;
}
table.FreezePanes(3 ,1); //前二行冻结
//文字水平垂直对齐中心
table.Range[table.FirstRow, table.FirstColumn, table.LastRow, table.LastColumn].Style.HorizontalAlignment = HorizontalAlignType.Center; //水平对齐
table.Range[table.FirstRow, table.FirstColumn, table.LastRow, table.LastColumn].Style.VerticalAlignment = VerticalAlignType.Center; //垂直对齐
//保存的指定位置
try
{
string storeLoacation = "D:\\Data\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".xls";
WB.SaveToFile(storeLoacation, ExcelVersion.Version97to2003);
}
catch (Exception e)
{
string storeLoacation = "C:\\Data\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".xls";
WB.SaveToFile(storeLoacation, ExcelVersion.Version97to2003); //引用Spire.License.dll文件
}
}