Excel 导入并导出结果集
1、controler代码:
/// <summary>
/// 导入预归类意见书
/// </summary>
/// <param name="uploadfile"></param>
/// <returns></returns>
[HttpPost]
[ValidateAntiForgeryToken]
public FileResult INPUTExcel(IEnumerable<HttpPostedFileBase> uploadfile)
{
string strvalue = string.Empty;
byte[] fileContents = Encoding.Default.GetBytes("暂无数据!");
SsoIdentity identity = this.User.Identity as SsoIdentity;
try
{
string SavePath = string.Empty;
bool bResult = false;
#region<<将Excel文件保存到服务器>>
foreach (var file in uploadfile)
{
string FileName = Path.GetFileName(file.FileName);
string PathR = Server.MapPath("~/UpLoadFile/PreClassified/");
bResult = FileHelper.IsExistDirectory(PathR);
if (!bResult)
{
FileHelper.CreateDirectory(PathR);
}
SavePath = Path.Combine(PathR, FileName);
file.SaveAs(SavePath);
}
#endregion
if (!string.IsNullOrWhiteSpace(SavePath))
{
LoginInfo loginInfo = new LoginInfo();
UserHelper.GetUserInfo(false, ref loginInfo, identity);
//如果存在已存在数据选择是否覆盖的预归类意见书列表
bResult = _ibll.InputClassificationLabDecision(SavePath, ref fileContents,loginInfo.CustomCode); //FileHelper.UnLockFile(SavePath);
System.IO.File.Delete(SavePath);//添加导入完成之后在服务器端删除上传到服务器的EXCEL文件 strvalue = string.Format("三统一帐号{0} 执行预归类意见书管理子系统中预归类意见书 ", loginInfo.LoginName);
if (!bResult)
{
UserOperateLogHelper.WriteOperateLog(strvalue, EnumActionOperatonType.InPut, (int)EnumActionExecutedStatus.Error, identity,
(int)EnumSysFlags.PreClassification);
}
UserOperateLogHelper.WriteOperateLog(strvalue, EnumActionOperatonType.InPut, (int)EnumActionExecutedStatus.Success, identity,
(int)EnumSysFlags.PreClassification);
}
}
catch(Exception ex)
{
LogHelper.Write(ex);
}
return File(fileContents, "application/ms-excel", "ImportPerBooksResult.xls");
}
2.BLL层代码
(1)处理Excel文件:
/// <summary>
/// 导入预归类意见书
/// </summary>
/// <param name="fileName"></param>
/// <param name="btyBytes"></param>
/// <returns></returns>
public bool InputClassificationLabDecision(string fileName, ref byte[] btyBytes, string CGAC_CO)
{
IWorkbook workbook = null;
List<PreClassificationOpBook> lst = new List<PreClassificationOpBook>();
FileStream fs = null;
List<string> lstresult = null;
//string sheetName = null;
bool bResult = true;
ISheet sheet = null;
string filename = string.Format("MyClassificationLabDecision{0}.xls", DateTime.Now.ToString("HHmmssfff"));
int startRow = ;
try
{
using (fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
if (fileName.IndexOf(".xlsx") > ) // 2007版本
{
workbook = new XSSFWorkbook(fs);
}
else if (fileName.IndexOf(".xls") > ) // 2003版本
{
workbook = new HSSFWorkbook(fs);
}
if (workbook != null)
{
sheet = workbook.GetSheetAt();
if (sheet != null)
{
IRow firstRow = sheet.GetRow();
int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数
startRow = sheet.FirstRowNum + ;
//最后一列的标号
int rowCount = sheet.LastRowNum;
List<bool> lstdate = new List<bool>();
for (int i = startRow; i <= rowCount; ++i)
{
bool IsNullRow = true;
PreClassificationOpBook mdl = new PreClassificationOpBook();
IRow row = sheet.GetRow(i);
if (row == null) continue; //没有数据的行默认是null
for (int j = row.FirstCellNum; j < cellCount; ++j)
{
bool ibresult = false;
var cellValue=row.GetCell(j);
var rowValue = cellValue == null?"":cellValue.ToString();
if (!string.IsNullOrWhiteSpace(rowValue) || !IsNullRow)
{
mdl = AddModelField(j, mdl, rowValue, ref ibresult);
if (j == )//如果列为生效日期列
{
lstdate.Add(ibresult);
}
IsNullRow = false;
}
}
if (!IsNullRow)
{
lst.Add(mdl);
}
}
//不采取全部一起提交的方式 每一条执行一次SaveChanage
AddModelList(lst, lstdate, ref lstresult,CGAC_CO);
}
}
}
}
catch (IOException ex)
{
LogHelper.Write(ex);
bResult = false;
}
catch (SqlException ex)
{
LogHelper.Write(ex);
bResult = false;
}
finally
{
if (fs != null)
{
fs.Dispose();
}
//导出结果集
Dictionary<string, string> Dic = GETMATCHUP();
Dic["CGAC_CO"] = "关区代码";
Dic.Remove("IsEffect");
FileHelper.ExExcelDouble<PreClassificationOpBook>(lst, filename, ref btyBytes, Dic, lstresult);
}
return bResult;
}
(2)Excel列存入model实体类
/// <summary>
/// 向Model中添加字段值
/// </summary>
/// <param name="i"></param>
/// <param name="mdl"></param>
/// <param name="row"></param>
/// <param name="ibresult"></param>
/// <returns></returns>
private PreClassificationOpBook AddModelField(int i, PreClassificationOpBook mdl, string rowValue, ref bool ibresult)
{ switch (i)
{
//case 0://第一行为流水号
// {
// mdl.SEQ_NO = rowValue;
// break;
// }
case ://预归类意见书编号
{
mdl.PCS_NO_S = rowValue;
break;
}
case ://经营单位(委托方)名称
{
mdl.TRADE_NAME = rowValue;
break;
}
case ://经营单位(委托方)企业代码
{
mdl.TRADE_CO = rowValue;
break;
}
case ://商品名称(中文)
{
mdl.G_NAME = rowValue;
break;
}
case ://规格型号
{
mdl.G_MODEL = rowValue;
break;
}
case ://商品名称(英文名称)
{
mdl.G_NAME_ENG = rowValue;
break;
}
case ://商品名称(其他名称)
{
mdl.G_NAME_OTR = rowValue;
break;
}
case ://商品描述(货物型号、规格、成份及用途)
{
mdl.G_DESCRIPTION = rowValue;
break;
}
case ://归类结论
{
mdl.CODE_TS = rowValue;
break;
}
case ://归类依据或理由
{
mdl.NOTE = rowValue;
break;
}
case ://预归类单位名称
{
mdl.AGENT_NAME = rowValue;
break;
}
//case 11://预归类数据导入单位名称
// {
// mdl.AGENT_INPUT_NAME = rowValue;
// break;
// }
case ://联系电话
{
mdl.AGENT_TEL = rowValue;
break;
}
//case 13://关区代码
// {
// mdl.CGAC_CO = rowValue;
// break;
// }
case ://生效日期
{
DateTime dt = DateTime.Now;
bool bResult = ToolsHelper.CheckTime(rowValue.Replace("月", ""), ref dt);
if (bResult)
{
mdl.EFFECTIVE_DATE = dt;
}
ibresult = bResult;
break;
}
}
return mdl;
}
3.导出导入结果集
(1)固定列最后加一列导入结果列
/// <summary>
/// 将一组对象导出成EXCEL
/// </summary>
/// <typeparam name="T">要导出对象的类型</typeparam>
/// <param name="objList">一组对象</param>
/// <param name="fileName">导出后的文件名</param>
/// <param name="columnInfo">列名信息</param>
/// <param name="btyBytes"></param>
public static bool ExExcelDouble<T>(List<T> objList, string fileName, ref byte[] btyBytes, Dictionary<string, string> columnInfo = null,
List<string> lststring = null) where T : class
{
bool bResult = false;
try
{
//if (objList.Count > 50000)
//{
// btyBytes = new byte[] { };
// bResult = ExExcel<T>(objList, fileName, ref btyBytes, columnInfo, lststring);
// return bResult;
//}
HSSFWorkbook workbook = new HSSFWorkbook();
//在工作薄中建立工作表
HSSFSheet sheet = workbook.CreateSheet() as HSSFSheet;
sheet.SetColumnWidth(, * );
if (columnInfo != null && columnInfo.Count == ) { return false; }
//生成EXCEL的HTML
string excelStr = "";
Type myType = null;
if (objList.Any())
{
myType = objList[].GetType();
//根据反射从传递进来的属性名信息得到要显示的属性
List<PropertyInfo> myPro = new List<PropertyInfo>();
PropertyInfo[] properties = myType.GetProperties();
int m = ;
if (columnInfo != null)
{
var rowheader = sheet.CreateRow();
rowheader.Height = * ;
foreach (string cName in columnInfo.Keys)
{
PropertyInfo p = myType.GetProperty(cName);
if (p != null)
{
myPro.Add(p);
rowheader.CreateCell(m).SetCellValue(columnInfo[cName]);
m++;
}
}
if (lststring != null)
{
rowheader.CreateCell(myPro.Count).SetCellValue("导入提示");
}
}
//如果没有找到可用的属性则结束
if (myPro.Count == ) { return bResult; }
int i = ;//lststring 计数
foreach (T obj in objList)
{
int n = ;
if (sheet != null)
{
var sheetrow = sheet.CreateRow(i);
sheetrow.Height = sheetrow.Height = * ;
foreach (PropertyInfo p in myPro)
{
dynamic val = p.GetValue(obj, null) ?? "";
string valtype = val.GetType().ToString();
if (valtype.ToLower().IndexOf("decimal", StringComparison.Ordinal) > -)
{
val = Convert.ToDouble(val);
}
else if (valtype.ToLower().IndexOf("datetime", StringComparison.Ordinal) > -)
{
val = val.ToString("yyyy-MM-dd HH:mm:ss");
if (val.Equals("0001-01-01 00:00:00"))
{
val = "";
}
}
sheetrow.CreateCell(n).SetCellValue(val);
n++;
} if (lststring != null)
{
sheetrow.CreateCell(n).SetCellValue(lststring[i - ]);
}
} Thread.Sleep();
i++;
}
}
else
{
if (sheet != null) sheet.CreateRow().CreateCell().SetCellValue("暂无数据!");
} using (MemoryStream ms = new MemoryStream())
{
workbook.Write(ms);
if (btyBytes != null)
{
btyBytes = ms.ToArray();
}
else
{
btyBytes = ms.ToArray(); HttpResponse rs = System.Web.HttpContext.Current.Response;
rs.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
rs.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName,System.Text.Encoding.UTF8));
rs.ContentType = "application/ms-excel";
rs.BinaryWrite(btyBytes);
rs.End();
}
ms.Flush();
ms.Position = ;
workbook = null;
}
//输出EXCEL
bResult = true;
}
catch (Exception ex)
{
LogHelper.Write(ex);
}
return bResult;
}
(2)动态列(不固定列)导入导出结果集
/// <summary>
/// 同义词导入
/// </summary>
/// <typeparam name="T">要导出对象的类型</typeparam>
/// <param name="objList">一组对象</param>
/// <param name="fileName">导出后的文件名</param>
/// <param name="columnInfo">列名信息</param>
/// <param name="MaxColNum">最大列数</param>
/// <param name="btyBytes"></param>
public static bool ExRandomColExcel<T>(List<T> objList, string fileName, ref byte[] btyBytes, Dictionary<string, string> columnInfo = null,
List<string> lststring = null, int MaxColNum = ) where T : class
{
bool bResult = false;
try
{
HSSFWorkbook workbook = new HSSFWorkbook();
//在工作薄中建立工作表
HSSFSheet sheet = workbook.CreateSheet() as HSSFSheet;
sheet.SetColumnWidth(, * ); if (columnInfo != null && columnInfo.Count == ) { return false; }
//生成EXCEL的HTML
Type myType = null;
if (objList.Any())
{
CellType cellType = new CellType(); myType = objList[].GetType();
//根据反射从传递进来的属性名信息得到要显示的属性
List<PropertyInfo> myPro = new List<PropertyInfo>();
PropertyInfo[] properties = myType.GetProperties();
int m = ;
if (columnInfo != null)
{
var rowheader = sheet.CreateRow();
rowheader.Height = * ;
if (lststring != null)
{
rowheader.CreateCell(myPro.Count).SetCellValue("导入提示");
}
for (int i = ; i < MaxColNum; i++)
{
m++;
PropertyInfo p = myType.GetProperty(columnInfo.ElementAtOrDefault(i > columnInfo.Count - ? columnInfo.Count - : i).Key);
if (p != null)
{
myPro.Add(p);
rowheader.CreateCell(m).SetCellValue(
columnInfo.ElementAtOrDefault(i > columnInfo.Count - ? columnInfo.Count - : i).Value);
}
}
}
//如果没有找到可用的属性则结束
if (myPro.Count == ) { return bResult; }
int rowCount = ;//lststring 计数
foreach (T obj in objList)
{
PropertyInfo[] pro = obj.GetType().GetProperties();
int n = ;
if (sheet != null)
{
var sheetrow = sheet.CreateRow(rowCount);
sheetrow.Height = sheetrow.Height = * ;
//导入结果
if (lststring != null)
{
sheetrow.CreateCell(n).SetCellValue(lststring[rowCount - ]);
}
for (int j = ; j < MaxColNum; j++)
{
n++;
dynamic value = "";
dynamic val = pro[j > pro.Length - ? pro.Length - : j].GetValue(obj, null);
string listtype = val.GetType().ToString();
if (listtype.ToLower().IndexOf("list", StringComparison.Ordinal) > -)
{
foreach (var item in val)
{
j++;
value = item;
string valtype = value.GetType().ToString();
if (valtype.ToLower().IndexOf("decimal", StringComparison.Ordinal) > -)
{
value = Convert.ToDouble(value);
}
else if (valtype.ToLower().IndexOf("datetime", StringComparison.Ordinal) > -)
{
value = value.ToString("yyyy-MM-dd HH:mm:ss");
}
sheetrow.CreateCell(n).SetCellValue(value);
n++;
}
if (j > pro.Length - )
{
break;
}
}
else
{
value = pro[j].GetValue(obj, null);
string valtype = value.GetType().ToString();
if (valtype.ToLower().IndexOf("decimal", StringComparison.Ordinal) > -)
{
value = Convert.ToDouble(value);
}
else if (valtype.ToLower().IndexOf("datetime", StringComparison.Ordinal) > -)
{
value = value.ToString("yyyy-MM-dd HH:mm:ss");
}
sheetrow.CreateCell(n).SetCellValue(value);
}
}
}
Thread.Sleep();
rowCount++;
}
}
else
{
if (sheet != null) sheet.CreateRow().CreateCell().SetCellValue("暂无数据!");
} using (MemoryStream ms = new MemoryStream())
{
workbook.Write(ms);
if (btyBytes != null)
{
btyBytes = ms.ToArray();
}
else
{
btyBytes = ms.ToArray();
HttpResponse rs = System.Web.HttpContext.Current.Response;
rs.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
rs.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);
rs.ContentType = "application/ms-excel";
rs.BinaryWrite(btyBytes);
rs.End();
}
ms.Flush();
ms.Position = ;
workbook = null;
}
//输出EXCEL
bResult = true;
}
catch (Exception ex)
{
LogHelper.Write(ex);
}
return bResult;
}
Excel 导入并导出结果集的更多相关文章
- C# Excel导入、导出【源码下载】
本篇主要介绍C#的Excel导入.导出. 目录 1. 介绍:描述第三方类库NPOI以及Excel结构 2. Excel导入:介绍C#如何调用NPOI进行Excel导入,包含:流程图.NOPI以及C#代 ...
- ASP.NET MVC5+EF6+EasyUI 后台管理系统(63)-Excel导入和导出-自定义表模导入
系列目录 前言 上一节使用了LinqToExcel和CloseXML对Excel表进行导入和导出的简单操作,大家可以跳转到上一节查看: ASP.NET MVC5+EF6+EasyUI 后台管理系统(6 ...
- C# Excel导入、导出
本篇主要介绍C#的Excel导入.导出. 目录 1. 介绍:描述第三方类库NPOI以及Excel结构 2. Excel导入:介绍C#如何调用NPOI进行Excel导入,包含:流程图.NOPI以及C#代 ...
- JXLS (Excel导入、导出工具使用)
JXLS (Excel导入.导出工具使用) 1:简介: jxls是一个简单的.轻量级的excel导出库,使用特定的标记在excel模板文件中来定义输出格式和布局.java中成熟的excel导出工具有p ...
- ASP.NET MVC5+EF6+EasyUI 后台管理系统(63)-Excel导入和导出
系列目录 昨天文章太过仓促没有补充导出的示例源码,在者当时弄到到很晚没时间做出导出功能,对阅读理解造成影响,现补充一份示例源码,顺便补充导出的功能说明,望理解 示例代码下载 https://yun ...
- winform之excel导入和导出
引用命名空间 using Microsoft.Office.Interop.Excel;DataGridView 导出到Excel public static void SaveAs(DataGr ...
- excel 导入 与 导出
Excel导入 public ActionResult Excel(HttpPostedFileBase file) { HttpPostedFileBase fi ...
- ASP.NET MVC5+EF6+EasyUI 后台管理系统(87)-MVC Excel导入和导出
本文示例代码下载: 链接:http://pan.baidu.com/s/1jHBdgCA 密码:hzh7 ps:Vs数据库脚本在解压目录下,修改web.config数据库链接,示例代码包含:导入,导出 ...
- ASP.NET MVC5+EF6+EasyUI 后台管理系统(88)-Excel导入和导出-自定义表模导出
前言 之前说了导入和导出,也提供了自定义的表模的导入,可见LinqToExcel可以做的事情不仅仅如此 这次我们来演示比较复杂的导出Excel,导出复杂的Excel与导入复杂的Excel原理基本是一样 ...
随机推荐
- Redis - 常用命令操作
常用命令keys: keys * 查看符合条件的所有key exists: exists key 查看key是否存在 del: del k ...
- asp登陆例子,asp,mssql,登陆
login.aspx文件 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="log ...
- [转]Golang Gob编码
Golang Gob编码 2012-08-24 09:47 by 轩脉刃, 5119 阅读, 1 评论, 收藏, 编辑 gob是Golang包自带的一个数据结构序列化的编码/解码工具.编码使用Enco ...
- Magento架构师的笔记-----Magento显示当前目录的父分类和子分类的分类名
在Magento目录的分类页面里,希望在左侧导航获取到父分类和子分类,可以用以下方法:打开app/your_package/your_themes/template/catalog/navigatio ...
- Autoresizing和AutoLayout
1 使用Autoresizing的方式进行界面布局 1.1 问题 Autoresizing是IOS旧版的自动布局技术,现在仍然被很多企业使用.本案例将学习如何使用Autoresizing完成界面的布局 ...
- matlab自带princomp(PCA降维方式)
matlab 中自带的函数就不必怀疑. princomp:principal componet analysis (PCA). [COEFF,SCORE,latent,tsquare]=princom ...
- mysql 日期 时间戳 转换
/***************************************************************************************** * mysql 日 ...
- apache2将http自动指向https
<VirtualHost *:80> RewriteEngine On RewriteCond %{HTTPS} off RewriteRule (.*) https://%{HTTP_H ...
- VIM键盘快捷键映射
http://www.jianshu.com/p/216811be226b
- 说说Audition消除歌曲中的人声
今天再说说消除人声,音乐中人声的消除有多种方法,但都很难完全消除,而且效果越好越难消除,一首音效极佳的立体声歌曲是无法完全消除人声的.本人常用的是以下三种方法.第1种如下图,此方法简单,但是完成后变成 ...