项目场景:
提示:前端点击导出文件,生成Excel。Enumerable对象生成Excel文件(反射、泛型方法、字典)。
分析:
public ActionResult DownChange()
{
string filename = "模板.xls";
string root = Server.MapPath("~/File/文件模板");
string filePath = Path.Combine(root, filename);
string sheetName = "Sheet1";
List<RepositorySampleData> repositorySampleData = new List<RepositorySampleData>();
repositorySampleData = _ISampleDataRepository.RepositorySampleDatas/*.Where(a => a.意见 != null && a.意见.Contains("不保留"))*/.Take(100).ToList();
Dictionary<string, string> table = new Dictionary<string, string>();
table.Add("SortNum", "序号");
table.Add("状态", "状态");
table.Add("库存","库位");
table.Add("编号", "编号");
table.Add("型号", "型号");
NPIOLISToExcel(repositorySampleData, table, filePath, sheetName);
string s = MimeMapping.GetMimeMapping(filename);
return Content("/File/文件模板/" + filename);
}
/// <summary>
/// 生成Excel文件
/// </summary>
/// <typeparam name="T">数据类型</typeparam>
/// <param name="list">数据列表</param>
/// <param name="table">字典类型键值对</param>
/// <param name="FilePath">生成文件路径</param>
/// <param name="sheetName">生成Excel的sheet名称</param>
public void NPIOLISToExcel<T>(List<T> list, Dictionary<string,string> table, string FilePath,string sheetName="")
{
if (Path.GetExtension(FilePath).ToLower()==".xls".ToLower())
{
HSSFWorkbook wk = new HSSFWorkbook();//创建工作薄
ISheet sheet = wk.CreateSheet(sheetName);
//创建标题
IRow row = sheet.CreateRow(0);//创建第0行
var title = typeof(T).GetProperties();
int num = 0;
foreach (var ht in table)
{
foreach (var item in title)
{
if (item.Name.ToString() == ht.Key.ToString())
{
ICell cell = row.CreateCell(num++);
cell.SetCellValue(ht.Value.ToString());
}
}
}
int j = 1;
foreach (var item in list)
{
int sort = 0;
row = sheet.CreateRow(j++);
foreach (var ht in table)
{
var temp = Convert.ToString(item.GetType().GetProperty(ht.Key.ToString()).GetValue(item, null));
ICell cell = row.CreateCell(sort++);
cell.SetCellValue((string)temp);
}
}
using (FileStream fs = System.IO.File.OpenWrite(FilePath)) //打开一个xls文件,如果没有则自行创建,如果存在myxls.xls文件则在创建是不要打开该文件!
{
wk.Write(fs);//向打开的这个xls文件中写入mySheet表并保存。
}
}
}
方案:
提示:点击下载,导出table数据,生成Excel附件。对附件内容进行修改,然后提交附件,读取修改后的附件,进行数据库更新(此功能之后完成)