protected void btnDaochu_Click(object sender, EventArgs e)
{
string filePath = "";
bool check = false;
try
{
Log.WriteLog("执行数据作成(Excel)处理开始", CommConst.LOG_NORMAL, PageId);
polybasic Polybasic = new polybasic();
Polybasic=GetSearchInfo();
//出力操作
DataTable dtSource = new DataTable();
dtSource = depbl.GetmasdictInfo(Polybasic).Tables[0];
if (this.dgMst1.Rows.Count>0)
{
if (dtSource.Rows.Count == 0 || dtSource == null)
{
ShowMsgBox(Messager.GetMessageInfo2("MSG_POC_01"));
}
else if (dtSource.Rows.Count > 0)
{
System.Data.DataTable dt = dtSource;
string filename = "NOKSJZC" + "_" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".xls";
//临时存放路径
filePath = Server.MapPath("~/Template/" + filename);
//Excel模版文件的路径excel的模板
string masterPath = Server.MapPath("~/Template/polybasic1.xlt");
//复制Excel模版
File.Copy(masterPath, filePath);
// 先把文件的属性读取出来
FileAttributes attrs = File.GetAttributes(filePath);
// 下面表达式中的 1 是 FileAttributes.ReadOnly 的值
// 此表达式是把 ReadOnly 所在的位改成 0,
attrs = (FileAttributes)((int)attrs & ~(1));
FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read);
HSSFWorkbook hssfworkbook = new HSSFWorkbook(file);
ISheet sheet = hssfworkbook.GetSheet("Sheet_polybasic");
for (int i = 0; i < dt.Rows.Count; i++)
{
sheet.CopyRow(0, i + 1);
}
for (int i = 0; i < dt.Rows.Count; i++)
{
//从第几行开始进行导出
IRow row = sheet.GetRow(i + 1);
row.GetCell(0).SetCellValue(i + 1);
row.GetCell(1).SetCellValue(dt.Rows[i]["type"].ToString());
row.GetCell(2).SetCellValue(dt.Rows[i]["type_name"].ToString());
row.GetCell(3).SetCellValue(dt.Rows[i]["code"].ToString());
row.GetCell(4).SetCellValue(dt.Rows[i]["code_name"].ToString());
row.GetCell(5).SetCellValue(dt.Rows[i]["code_name_cn"].ToString());
row.GetCell(6).SetCellValue(dt.Rows[i]["code_name_en"].ToString());
row.GetCell(7).SetCellValue(dt.Rows[i]["code_name_jp"].ToString());
row.GetCell(8).SetCellValue(dt.Rows[i]["memo"].ToString());
}
sheet.ForceFormulaRecalculation = true;
using (FileStream filess = File.OpenWrite(filePath))
{
hssfworkbook.Write(filess);
}
check = true;
// 输出副本的二进制字节流
HttpContext.Current.Response.Charset = "UTF-8"; // 或UTF-7 以防乱码
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.ContentType = "application/ms-excel";
Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(System.Text.Encoding.GetEncoding(65001).GetBytes(filename)));
Response.BinaryWrite(File.ReadAllBytes(filePath));
}
}
else
{
ShowMsgBox(Messager.GetMessageInfo2("MSG_POC_01"));
}
if (Session["polybasicManager" + CommConst.PAGE_DATASOURCE_SESSION] != null)
{
SetGdvListData(1);
}
}
catch (Exception ex)
{
Log.WriteLog("执行数据作成(Excel)处理异常,异常信息:" + ex.Message, CommConst.LOG_ERROR, PageId);
throw ex;
}
finally
{
Log.WriteLog("执行数据作成(Excel)处理结束", CommConst.LOG_NORMAL, PageId);
if (check)
{
//删除副本
File.Delete(filePath);
}
}
} |