1.项目添加Word和Excel的COM类型库引用
2.创建Excel工作表
//定义Excel操作对象
Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
//定义Excel工作表
Microsoft.Office.Interop.Excel.Worksheet worksheet = excelApp.Workbooks.Add().Worksheets[1];
3.设置Excel表格的标题
//设置标题样式[2, 2]开始
worksheet.Cells[2, 2] = "成绩单"; //设置标题内容
worksheet.Cells[2, 2].RowHeight = 25; //高度
Microsoft.Office.Interop.Excel.Range range = worksheet.get_Range("B2", "H2"); //这里Range和get_Range都不会给提示
range.Merge(0); //合并为标题
range.Borders.Value = 1; //设置表头的边框
range.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter; //单元格内容居中
range.Font.Size = 15;
4.加载数据进入Excel表格
//获取总列数和总行数
int columnCount = dgv.ColumnCount;
int rowCount = dgv.RowCount;
//显示列标题
for (int i = 0; i < columnCount; i++)
{
//从第三行开始
worksheet.Cells[3, i + 2] = dgv.Columns[i].HeaderText; //获取dgv列标题
worksheet.Cells[3, i + 2].Borders.value = 1; //这个Borders不会提示
worksheet.Cells[3, i + 2].RowHeight = 23;
}
//显示表格数据
for (int i = 0; i < rowCount-1; i++)
{
for (int n = 0; n < columnCount; n++)
{
//从第三行开始
worksheet.Cells[i + 4, n + 2] = dgv.Rows[i + 1].Cells[n].Value; //获取dgv列标题
worksheet.Cells[i + 4, n + 2].Borders.value = 1; //这个Borders不会提示
worksheet.Cells[i + 4, n + 2].RowHeight = 23;
}
}
//设置列宽和数据一致
worksheet.Columns.AutoFit();
5.显示和释放工作簿对象
//预览
excelApp.Visible = true;
//excelApp.Sheets.PrintPreview(false); //要打印就用这个
//释放对象
excelApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
excelApp = null;