//生成Excel文件的代码
protected void ExportExcel()
{
Microsoft.Office.Interop.Excel.Application excel = null;
Microsoft.Office.Interop.Excel.Worksheet ws = null;
Microsoft.Office.Interop.Excel.Workbook wb = null;
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); //设置输出流为简体中文
try
{
excel = new Microsoft.Office.Interop.Excel.Application();
wb = excel.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet); // 创建工作簿
ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets[1]; // 创建工作页
int iMaxRow = dt.Rows.Count;
int iMaxCol = dt.Columns.Count;
// 设置格式
ws.get_Range(ws.Cells[1, 1], ws.Cells[1, iMaxCol]).Font.Name = "黑体";
ws.get_Range(ws.Cells[1, 1], ws.Cells[1, iMaxCol]).Font.Bold = true;
ws.get_Range(ws.Cells[1, 1], ws.Cells[iMaxRow + 1, iMaxCol]).Borders.LineStyle = 1;
// 设置标题
excel.Cells[1, 1] = "编号"; //第一行第一列
excel.Cells[1, 2] = "名称"; //第一行第二列
// 填充数据
for (int iRow = 0; iRow < iMaxRow; iRow++)
{
for (int iCol = 0; iCol < iMaxCol; iCol++)
{
excel.Cells[iRow + 2, iCol + 1] = dt.Rows[iRow][iCol].ToString(); //第N行第N列填充
}
}
// 保存Excel路径
excel.Save(Server.MapPath("~/") + "Excel/room2.xls");
// 打开Excel
excel.Visible = true;
}
catch (Exception ex)
{
}
}
如果出现 检索 COM 类工厂中 CLSID 为{00024500-0000-0000-C000-000000000046}的组件时失败,错误:80070005,就按照下面的做就可以了:
http://blog.csdn.net/wei_jie_zhang/article/details/8282282