C#生成Excel保存到服务器端并下载

时间:2021-04-21 17:51:17
using MongoDB.Bson;
using Newtonsoft.Json.Linq;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using Zluo.CMember.Entity;
using Zluo.CMember.Interface;
using Zluo.CMember.Service;
using Zluo.CMember.Web.RequestParam;
using Zluo.CMember.Web.RequestParam.Account;
using Zluo.CMember.Web.RequestParam.Order;
using Zluo.Common;
using Zluo.Common.CMember;
using Zluo.SessionCached;
public void CreateExport()
{
try
{
string fileName = "ErrorSongIds.xls"; // 文件名称
string filePath = Path.Combine(HttpRuntime.AppDomainAppPath, "Upload") + "/" + fileName;
// 1.检测是否存在文件夹,若不存在就建立个文件夹
string directoryName = Path.GetDirectoryName(filePath); if (!Directory.Exists(directoryName)) { Directory.CreateDirectory(directoryName); }
// 2.解析单元格头部,设置单元头的中文名称
HSSFWorkbook workbook = new HSSFWorkbook();
// 工作簿
ISheet sheet = workbook.CreateSheet("失败歌曲");
// 工作表
IRow row = sheet.CreateRow(0); row.CreateCell(0).SetCellValue("原始ID");
row.CreateCell(
1).SetCellValue("歌曲名称");
row.CreateCell(
2).SetCellValue("歌手名");
row.CreateCell(
3).SetCellValue("失败原因");
//_songListService.getErrorExcel(uid);
BsonArray array = null;
int rowIndex = 1; BsonDocument bd = null;
if (array != null && array.Count > 0)
{
for (int i = 0; i < array.Count; i++)
{
IRow rowTmp
= sheet.CreateRow(rowIndex);
bd
= (BsonDocument)array[i];
if (bd != null)
{
rowTmp.CreateCell(
0).SetCellValue(bd.GetValue("sourceId").ToString());
rowTmp.CreateCell(
1).SetCellValue(bd.GetValue("songName").ToString());
rowTmp.CreateCell(
2).SetCellValue(bd.GetValue("singerName").ToString());
rowTmp.CreateCell(
3).SetCellValue(string.IsNullOrEmpty(bd.GetValue("errorReason").ToString()) ? "" : bd.GetValue("errorReason").ToString());
rowIndex
++;
}
}
}
// 4.生成文件
FileStream file = new FileStream(filePath, FileMode.Create);
workbook.Write(file); file.Close();
Response.AppendHeader(
"Content-Disposition", "attachment;filename=ErrorSongIds.xls");
Response.ContentType
= "application/ms-excel";
Response.WriteFile(filePath);
Response.Flush();
Response.End();
}
catch (Exception ex) { throw ex; }
}

 由于没有找到哪里上传文件,需要NPOI.dll文件的给我留言哈,见谅咯。

 

附加动态加载Excel列和合并单元格的代码:

public void CreateExport()
{
try
{
string fileName = "Members.xls"; // 文件名称
string filePath = Path.Combine(HttpRuntime.AppDomainAppPath, "Template") + "/" + fileName;
// 1.检测是否存在文件夹,若不存在就建立个文件夹
string directoryName = Path.GetDirectoryName(filePath);
if (!Directory.Exists(directoryName))
{
Directory.CreateDirectory(directoryName);
}
// 2.解析单元格头部,设置单元头的中文名称
HSSFWorkbook workbook = new HSSFWorkbook();

// 工作簿
ISheet sheet = workbook.CreateSheet("会员列表");

#region 设置Excel表格第一行的样式
IRow titleInfo
= sheet.CreateRow(0);
ICell cellTitle
= titleInfo.CreateCell(0);
cellTitle.SetCellValue(
"会员信息批量录入模板");
ICellStyle titleStyle
= workbook.CreateCellStyle();
IFont titleFont
= workbook.CreateFont();
titleFont.FontHeightInPoints
= 25;
titleFont.Boldweight
= short.MaxValue;//字体加粗
titleStyle.SetFont(titleFont);
cellTitle.CellStyle
= titleStyle;

#endregion


IRow dataFields
= sheet.CreateRow(2);


ICellStyle style
= workbook.CreateCellStyle();//创建样式对象
style.Alignment = HorizontalAlignment.CENTER;//水平对齐
style.VerticalAlignment = VerticalAlignment.CENTER;//垂直对齐
IFont font = workbook.CreateFont(); //创建一个字体样式对象
font.FontName = "宋体"; //和excel里面的字体对应
font.Color = new HSSFColor.RED().GetIndex();//颜色参考NPOI的颜色对照表(替换掉PINK())
font.FontHeightInPoints = 10;//字体大小
font.Boldweight = short.MaxValue;//字体加粗
style.SetFont(font); //将字体样式赋给样式对象
sheet.SetColumnWidth(0, 20 * 256);//设置列宽

string[] colums = { "*会员卡号", "*会员手机", "*会员姓名", "*会员等级", "会员性别", "电子邮箱", "会员状态", "固定电话", "永久有效", "身份证号", "开卡费用", "会员地址", "备注信息" };
ICell Cell
= null;
for (int i = 0; i < colums.Count(); i++)
{
Cell
= dataFields.CreateCell(i);
Cell.CellStyle
= style;
Cell.SetCellValue(colums[i]);
sheet.SetColumnWidth(i,
17 * 256);
}
sheet.AddMergedRegion(
new CellRangeAddress(0, 0, 0, colums.Count()));//合并单元格
// 4.生成文件
FileStream file = new FileStream(filePath, FileMode.Create);
workbook.Write(file); file.Close();
Response.AppendHeader(
"Content-Disposition", "attachment;filename=Members.xls");
Response.ContentType
= "application/ms-excel";
Response.WriteFile(filePath);
Response.Flush();
Response.End();
}
catch (Exception ex) { throw ex; }
}