Interop.Excel.dll这个DLL(需安装office2003 excel,下面的说明及示例都是基于office2003的,版本不同调用可能会不一样) 页面的命名空间引用 using Excel; 下面是调用模板的一段代码
复制代码 代码如下:
#region 使用模板导出Excel表 case "ReportByTemp": {
DataView dv = Cache["ReportByTemp"] as DataView; //建立一个Excel.Application的新进程 Excel.Application app = new Excel.Application(); if (app == null) { return; } app.Visible = false; app.UserControl = true; Workbooks workbooks = app.Workbooks; _Workbook workbook = workbooks.Add(template_path + "\\EXCEL测试模板.xls");//这里的Add方法里的参数就是模板的路径 Sheets sheets = workbook.Worksheets; _Worksheet worksheet = (_Worksheet)sheets.get_Item(1);//模板只有一个sheet表 if (worksheet == null) { return; }
int rowNum = 0; for (int i = 0; i < dv.Count; i++) { rowNum = i + 1; worksheet.Cells[3 + i, 1] = rowNum; worksheet.Cells[3 + i, 2] = dv[i].Row[0].ToString(); worksheet.Cells[3 + i, 3] = dv[i].Row[1].ToString();
excelOperate.SetBold(worksheet, worksheet.Cells[3 + i, 1], worksheet.Cells[3 + i, 1]); //黑体 excelOperate.SetHAlignCenter(worksheet, worksheet.Cells[3 + i, 1], worksheet.Cells[3 + i, 3]);//居中 worksheet.get_Range(worksheet.Cells[3 + i, 1], worksheet.Cells[3 + i, 3]).Borders.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Black);