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;
6.补充
一:
在前面老是用到Microsoft.Office.Interop.Excel这个命名空间,可以给它起个别名方便书写
例如:using ApExcel = Microsoft.Office.Interop.Excel;
二:
创建sheet表格的另外写法
ApExcel.Application application = new ApExcel.Application();
ApExcel.Workbooks workbooks1 = application.Workbooks;
ApExcel.Workbook wbk = null;
try
{
wbk = workbooks1.Add(true);
ApExcel.Worksheet sheet = wbk.Worksheets[0];
sheet.Name = "sheet1";
}
三:给excel单元格赋值的另外写法
文章来源:https://www.toymoban.com/news/detail-569944.html
ApExcel.Range range = sheet.Cells[1, 1];
range.Value = "aaa";
文章来源地址https://www.toymoban.com/news/detail-569944.html
到了这里,关于C# Winfrom将DataGridView数据导入Excel的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!