简单导出下载excel的方法

简单导出excel方法
/// <summary>
/// Excel打包下载
/// </summary>
/// <returns></returns>
[HttpGet]
public FileResult Export()
{
//Excel表格 存储路径
string path = Server.MapPath(string.Format("/Template/{0}.xls", DateTime.Now.ToString("yyyyMMddHHmmssffff")));
//获取要导出的数据
System.Data.DataTable dt = new System.Data.DataTable();
SqlConnection con = new SqlConnection("Data Source=LENOVO-PC;Initial Catalog=cs;Integrated Security=True");
SqlDataAdapter dap = new SqlDataAdapter("select * from [table]",con);
dap.Fill(dt);

////删除表中不需要导出的列
//dt.Columns.Remove("ComId");//历史记录id
//dt.Columns.Remove("UserId");//用户id

//修改列名
dt.Columns["id"].ColumnName = "协会名称";
dt.Columns["name"].ColumnName = "地址";

HSSFWorkbook workbook = new HSSFWorkbook();
ISheet sheet = string.IsNullOrEmpty(dt.TableName) ? workbook.CreateSheet("Sheet1") : workbook.CreateSheet(dt.TableName);//创建工作表

#region 标题
IRow row = sheet.CreateRow(0);//在工作表中添加一行
for (int i = 0; i < dt.Columns.Count; i++)
{
NPOI.SS.UserModel.ICell cell = row.CreateCell(i);//在行中添加一列
sheet.SetColumnWidth(i, 10 * 512);
cell.SetCellValue(dt.Columns[i].ColumnName);//设置列的内容
}
#endregion
#region 填充数据
for (int i = 1; i <= dt.Rows.Count; i++)//遍历DataTable行
{
DataRow dataRow = dt.Rows[i - 1];
row = sheet.CreateRow(i);//在工作表中添加一行
for (int j = 0; j < dt.Columns.Count; j++)//遍历DataTable列
{
NPOI.SS.UserModel.ICell cell = row.CreateCell(j);//在行中添加一列
cell.SetCellValue(dataRow[j].ToString());//设置列的内容
}
}
#endregion
#region 输出到Excel
MemoryStream ms = new MemoryStream();
workbook.Write(ms);
using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write))
{
byte[] bArr = ms.ToArray();
fs.Write(bArr, 0, bArr.Length);
fs.Flush();
}
#endregion
return File(path, "application/octet-stream", string.Format("本协会通讯录信息{0}项重点工作.xls", dt.Rows.Count));
}

posted @ 2018-12-05 16:04  清风不在已徐来  阅读(279)  评论(0编辑  收藏  举报