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;