.NET导出excel方法
2018-06-18 04:21:21来源:未知 阅读 ()
//导出
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)这个方法就行
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有
- Spire.Cloud.SDK for Java 合并、拆分Excel单元格 2020-06-09
- 「starter推荐」简单高效Excel 导出工具 2020-06-08
- 【Java-jxl插件】【Excel文件读写报错】jxl.read.biff.BiffE 2020-06-07
- excel如何分别实现按行读和按列读呢 2020-06-06
- Dubbo源码阅读-服务导出 2020-05-29
IDC资讯: 主机资讯 注册资讯 托管资讯 vps资讯 网站建设
网站运营: 建站经验 策划盈利 搜索优化 网站推广 免费资源
网络编程: Asp.Net编程 Asp编程 Php编程 Xml编程 Access Mssql Mysql 其它
服务器技术: Web服务器 Ftp服务器 Mail服务器 Dns服务器 安全防护
软件技巧: 其它软件 Word Excel Powerpoint Ghost Vista QQ空间 QQ FlashGet 迅雷
网页制作: FrontPages Dreamweaver Javascript css photoshop fireworks Flash