如最近公司项目中用到数据统计出Excel报表,从博客园找了相关的文章,第一次用到了Aspose.Cells,听说很强大。因为技术很菜,学习别的大牛的博客文章捣鼓了好久才搞出来,记录一下备忘。呵呵~
using Aspose.Cells;//Aspose.Cells引入的命名空间
/// <summary> /// 导出报表 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void imgbtnExportExcel_Click(object sender, ImageClickEventArgs e) { DataTable dt = helper.ExecuteDataTable(querySql); dt.TableName = "A"; if (dt.Rows.Count == 0) return; WorkbookDesigner designer = new WorkbookDesigner(); //Server.MapPath("./") string path = System.IO.Path.Combine(Server.MapPath("./"), "Templete/book1.xls"); designer.Open(path); designer.SetDataSource(dt); designer.Process(); //Save the excel file string fileToSave = System.IO.Path.Combine(Server.MapPath("./"), "Templete/JH_ManageExcel.xls"); if (File.Exists(fileToSave)) { File.Delete(fileToSave); } designer.Save(fileToSave, FileFormatType.Excel2003); //打开Excel文件 Process.Start(fileToSave); }
sqlhelper.cs public DataSet ExcuteDataSet(string sql) { SqlConnection con = new SqlConnection(connectionString); con.Open(); SqlDataAdapter dr = new SqlDataAdapter(sql, con); DataSet ds = new DataSet(); dr.Fill(ds); con.Close(); return ds; }
*****************************************第二种写法********************************出现保存窗口提示用户保存
DataTable dt = helper.ExecuteDataTable(querySql);
dt.TableName = "A";
if (dt.Rows.Count == 0)
return;
WorkbookDesigner designer = new WorkbookDesigner();
designer.Open(MapPath("~/Templete/book1.xls"));
designer.SetDataSource(dt);
designer.Process();
designer.Save(string.Format("JH-report.xls"), SaveType.OpenInExcel, FileFormatType.Excel2003, Response);
Response.Flush();
Response.Close();
designer = null;
Response.End();
自己建立一个兼容excel 模板,写好样式,填好公式。
效果如下: