NPOI模組 NPOI參考
//using NPOI;
//using NPOI.HSSF.UserModel; //Excel 2003檔案Model
//using NPOI.XSSFW.UserModel; //Excel 2007檔案Model
//using NPOI.SS.UserModel;
private void DataTableToExcelFile(DataTable dt)
{
//建立Excel 2003檔案
IWorkbook wb = new HSSFWorkbook();
ISheet ws;
//建立Excel 2007檔案
//IWorkbook wb = new XSSFWorkbook();
//ISheet ws;
if (dt.TableName != string.Empty)
{
ws = wb.CreateSheet(dt.TableName);
}
else
{
ws = wb.CreateSheet("Sheet1");
}
ws.CreateRow(0);//第一行為欄位名稱
for (int i = 0; i < dt.Columns.Count; i++)
{
ws.GetRow(0).CreateCell(i).SetCellValue(dt.Columns[i].ColumnName);
}
for (int i = 0; i < dt.Rows.Count; i++)
{
ws.CreateRow(i + 1);
for (int j = 0; j < dt.Columns.Count; j++)
{
ws.GetRow(i + 1).CreateCell(j).SetCellValue(dt.Rows[i][j].ToString());
}
}
FileStream file = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "Person.xls", FileMode.Create);//產生檔案
wb.Write(file);
file.Close();
}
// 寫入到客戶端
MemoryStream ms = new MemoryStream();
wb.Write(ms);
Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", HttpUtility.UrlEncode("Excel" + "_" + DateTime.Now.ToString("yyyy-MM-dd"), System.Text.Encoding.UTF8)));
Response.BinaryWrite(ms.ToArray());
Response.Flush();
Response.End();
wb = null;
ms.Close();
ms.Dispose();
沒有留言:
張貼留言