C# 导出 excel表格 (基础程序员)
导出的Helper
public void ExportExcel<T>(string fileName, List<T> list, Dictionary<string, string> dic) where T : class, new()
{
Type tp = typeof(T); //获取类型
var ps = tp.GetProperties(); //获取属性集合
//创建工作薄
var workbook = new HSSFWorkbook();
//创建表
var table = workbook.CreateSheet("sheet1");
//创建表头
var row = table.CreateRow(0);
for (int i = 0; i < ps.Length; i++)
{
if (dic.ContainsKey(ps[i].Name))
{
var cell = row.CreateCell(i);//创建单元格
cell.SetCellValue(dic[ps[i].Name]);
}
}
//模拟20行20列数据
for (var i = 1; i <= list.Count; i++)
{
//创建新行
var dataRow = table.CreateRow(i);
for (int j = 0; j < ps.Length; j++)
{
if (dic.ContainsKey(ps[j].Name))
{
var cell = dataRow.CreateCell(j);//创建单元格
cell.SetCellValue(ps[j].GetValue(list[i-1]).ToString());
}
}
}
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; FileName={0}", fileName));
Response.Charset = "GB2312";
Response.ContentEncoding = Encoding.GetEncoding("GB2312");
Response.ContentType = MimeMapping.GetMimeMapping(fileName);
workbook.Write(Response.OutputStream);
Response.Flush();
Response.Close();
}
private static object GetValue(string obj, PropertyInfo p)
{
object o = null;
switch (p.PropertyType.Name)
{
case "Int16":
o = Int16.Parse(obj);
break;
case "Int32":
o = Int32.Parse(obj);
break;
case "Int64":
o = Int64.Parse(obj);
break;
case "double":
o = double.Parse(obj);
break;
case "float":
o = float.Parse(obj);
break;
case "String":
o = obj.ToString();
break;
case "bool":
o = bool.Parse(obj);
break;
case "DateTime":
o = DateTime.Parse(obj);
break;
}
return o;
}
}
//导出的方法
public void ExPort()
{
//捕捉异常
try
{
List<WuPinModel> list = db.wuPinModel.Include("ShenModel")
.Where(x => x.WBit == 2).ToList(); //需要根据什么条件导出(根据已审核通过的导出)
Dictionary<string, string> dis = new Dictionary<string, string>();
dis.Add("Name", "物品名称"); //需要导出的字段
dis.Add("GuiGe", "物品规格"); //需要导出的字段
dis.Add("Num", "物品数量"); //需要导出的字段
dis.Add("WTime", "采购日期"); //需要导出的字段
dis.Add("Price", "物品单价"); //需要导出的字段
dh.ExportExcel<WuPinModel>("Wupin.xls", list, dis); //需实例化Helper
//地址,导出的数据模型,需要导出的字段
}
catch (Exception)
{
throw;
}
}
视图
<form action="http://localhost:44394/api/Shen/ExPort" method="post">
<input id="Submit1" type="submit" class="btn btn-info" value="导出" />
</form>