DataTable数据导出Excel 并且下载
public string Excel(System.Data.DataTable dt)
{
//模板的路径
string strUploadPath = HttpContext.Current.Server.MapPath("../template/");
//模板的名称
string strFileName = strUploadPath + "JobTicketTemplate.xlsx";
FileInfo TemplateFile = new FileInfo(strFileName);
//目标地址
string strPath = HttpContext.Current.Server.MapPath("../temp/");
//文件名称
string strNewFileName = System.DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx";
FileInfo newFile = new FileInfo(strPath + strNewFileName);
int intCount = 2;
using (OfficeOpenXml.ExcelPackage package = new OfficeOpenXml.ExcelPackage(newFile, TemplateFile))
{
// Worksheets指的是第几个Excel
OfficeOpenXml.ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
if (dt != null && dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
worksheet.Cell(i + intCount, 1).Value = dt.Rows[i]["Name"].ToString();
worksheet.Cell(i + intCount, 2).Value = dt.Rows[i]["RealName"].ToString();
worksheet.Cell(i + intCount, 3).Value = dt.Rows[i]["Company"].ToString();
worksheet.Cell(i + intCount, 4).Value = dt.Rows[i]["IdentityCard"].ToString();
worksheet.Cell(i + intCount, 5).Value = dt.Rows[i]["Province"].ToString();
worksheet.Cell(i + intCount, 6).Value = dt.Rows[i]["Email"].ToString();
worksheet.Cell(i + intCount, 7).Value = dt.Rows[i]["Mobile"].ToString();
}
}
package.Save();
}
return strNewFileName;
}