码迷,mamicode.com
首页 > Web开发 > 详细

.NET导出excel方法

时间:2017-02-10 14:16:53      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:dispose   head   ddb   int   response   try   system   http   pat   

//导出
private string outFileName = "";

private string fullFilename = "";
private Workbook book = null;
private Worksheet sheet = null;

private void AddHeader(string[] dt)
{
Cell cell = null;

int col = 0;
foreach (string item in dt)
{
cell = sheet.Cells[0, col];
cell.PutValue(item);
col++;
}

}

 


private void AddBody(DataTable dt, params int[] cl)
{
int cls = 0;
foreach (int item in cl)
{
for (int r = 0; r < dt.Rows.Count; r++)
{
sheet.Cells[r + 1, cls].PutValue(dt.Rows[r][item].ToString());
}
cls++;
}
}

 

public string Export(DataTable dt)
{
try
{
fullFilename = "Excel";
book = new Workbook();
//book.Open(tempfilename);
sheet = book.Worksheets[0];
sheet.Name = "数据";

//sheet.Name = sheetName;
//AddTitle(title, dt.Columns.Count);
AddHeader(new string[] { "列1", "列2", ...});
AddBody(dt, 列的个数);
sheet.AutoFitColumns();
//sheet.AutoFitRows();
fileName = System.DateTime.Now.ToString("yyyymmddhhmmss") + ".xls";
string SaveFilePath = @"\DownLoadFile\" + fileName;
book.Save(System.AppDomain.CurrentDomain.BaseDirectory + SaveFilePath);
this.fullFilename = System.AppDomain.CurrentDomain.BaseDirectory + SaveFilePath;
//byte[] array = File.ReadAllBytes(fullFilename);
FileStream fs = new FileStream(fullFilename, FileMode.Open);
byte[] data = new byte[fs.Length];
fs.Read(data, 0, data.Length);

BinaryWriter w = new BinaryWriter(fs);
MemoryStream ms = new MemoryStream(data);
w.Write(ms.ToArray());
w.Close();
w.Dispose();

fs.Close();
fs.Dispose();
//HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);
//HttpContext.Current.Response.BinaryWrite(ms.ToArray());
//HttpContext.Current.Response.End();
ms.Close();
ms.Dispose();
return fullFilename;
}
catch (Exception e)
{
return string.Empty;
}
}

 

调用时只需要Export(DataTable dt)这个方法就行

.NET导出excel方法

标签:dispose   head   ddb   int   response   try   system   http   pat   

原文地址:http://www.cnblogs.com/lzw-2017/p/6386071.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!