以前公司的一個物流商系統須要實現對訂單的批量導入和導出,翻閱了一些資料,最後考慮使用NPOI實現這個需求。css
在winform上面實現excel操做:http://www.cnblogs.com/CallmeYhz/p/4920293.html,NPOI的主頁:http://npoi.codeplex.com/html
NPOI 是 POI 項目的 .NET 版本。POI是一個開源的Java讀寫Excel、WORD等微軟OLE2組件文檔的項目, 使用 NPOI 你就能夠在沒有安裝 Office 或者相應環境的機器上對 WORD/EXCEL 文檔進行讀寫。NPOI是構建在POI 3.x版本之上的,它能夠在沒有安裝Office的狀況下對Word/Excel文檔進行讀寫操做。前端
Assembly名稱 | 模塊/命名空間 | 說明 |
NPOI.DLL | NPOI.POIFS | OLE2/ActiveX文檔屬性讀寫庫 |
NPOI.DLL | NPOI.DDF | 微軟Office Drawing讀寫庫 |
NPOI.DLL | NPOI.HPSF | OLE2/ActiveX文檔讀寫庫 |
NPOI.DLL | NPOI.HSSF | 微軟Excel BIFF(Excel 97-2003, doc)格式讀寫庫 |
NPOI.DLL | NPOI.SS | Excel公用接口及Excel公式計算引擎 |
NPOI.DLL | NPOI.Util | 基礎類庫,提供了不少實用功能,可用於其餘讀寫文件格式項目的開發 |
NPOI.OOXML.DLL | NPOI.XSSF | Excel 2007(xlsx)格式讀寫庫 |
NPOI.OOXML.DLL | NPOI.XWPF | Word 2007(docx)格式讀寫庫 |
NPOI.OpenXml4Net.DLL | NPOI.OpenXml4Net | OpenXml底層zip包讀寫庫 |
NPOI.OpenXmlFormats.DLL | NPOI.OpenXmlFormats | 微軟Office OpenXml對象關係庫 |
使用NuGet引入包,也能夠手動導入jquery
再添加一個ExcelHelper操做類,網絡上不少,我優化了一些細節,而且自測沒問題,附上ExcelHelper操做類:bootstrap
using System; using System.Data; using System.IO; using System.Text; using System.Web; using NPOI.HPSF; using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; namespace ExcelOperate { public class ExcelHelper { /// <summary> /// DataTable導出到Excel文件 /// </summary> /// <param name="dtSource">源DataTable</param> /// <param name="strHeaderText">表頭文本</param> /// <param name="strFileName">保存位置</param> /// <param name="strSheetName">工做表名稱</param> /// <Author>CallmeYhz 2015-11-26 10:13:09</Author> public static void Export(DataTable dtSource, string strHeaderText, string strFileName, string strSheetName, string[] oldColumnNames, string[] newColumnNames) { if (strSheetName == "") { strSheetName = "Sheet"; } using (MemoryStream ms = Export(dtSource, strHeaderText, strSheetName, oldColumnNames, newColumnNames)) { using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write)) { byte[] data = ms.ToArray(); fs.Write(data, 0, data.Length); fs.Flush(); } } } /// <summary> /// DataTable導出到Excel文件(無表頭)另外的是有表頭的 /// </summary> /// <param name="dtSource">源DataTable</param> /// <param name="strHeaderText">表頭文本</param> /// <param name="strFileName">保存位置</param> /// <param name="strSheetName">工做表名稱</param> /// <Author>CallmeYhz 2015-11-26 10:13:09</Author> public static void MyExport(DataTable dtSource, string strHeaderText, string strFileName, string strSheetName, string[] oldColumnNames, string[] newColumnNames) { if (strSheetName == "") { strSheetName = "Sheet"; } MemoryStream getms = new MemoryStream(); #region 爲getms賦值 if (oldColumnNames.Length != newColumnNames.Length) { getms= new MemoryStream(); } HSSFWorkbook workbook = new HSSFWorkbook(); //HSSFSheet sheet = workbook.CreateSheet();// workbook.CreateSheet(); ISheet sheet = workbook.CreateSheet(strSheetName); #region 右擊文件 屬性信息 { DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation(); dsi.Company = "http://....../"; workbook.DocumentSummaryInformation = dsi; SummaryInformation si = PropertySetFactory.CreateSummaryInformation(); if (HttpContext.Current.Session["realname"] != null) { si.Author = HttpContext.Current.Session["realname"].ToString(); } else { if (HttpContext.Current.Session["username"] != null) { si.Author = HttpContext.Current.Session["username"].ToString(); } } //填加xls文件做者信息 si.ApplicationName = "NPOI"; //填加xls文件建立程序信息 si.LastAuthor = "OA系統"; //填加xls文件最後保存者信息 si.Comments = "OA系統自動建立文件"; //填加xls文件做者信息 si.Title = strHeaderText; //填加xls文件標題信息 si.Subject = strHeaderText; //填加文件主題信息 si.CreateDateTime = DateTime.Now; workbook.SummaryInformation = si; } #endregion ICellStyle dateStyle = workbook.CreateCellStyle(); IDataFormat format = workbook.CreateDataFormat(); dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd"); #region 取得列寬 int[] arrColWidth = new int[oldColumnNames.Length]; for (int i = 0; i < oldColumnNames.Length; i++) { arrColWidth[i] = Encoding.GetEncoding(936).GetBytes(newColumnNames[i]).Length; } /* foreach (DataColumn item in dtSource.Columns) { arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length; } * */ for (int i = 0; i < dtSource.Rows.Count; i++) { for (int j = 0; j < oldColumnNames.Length; j++) { int intTemp = Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][oldColumnNames[j]].ToString()).Length; if (intTemp > arrColWidth[j]) { arrColWidth[j] = intTemp; } } /* for (int j = 0; j < dtSource.Columns.Count; j++) { int intTemp = Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][j].ToString()).Length; if (intTemp > arrColWidth[j]) { arrColWidth[j] = intTemp; } } * */ } #endregion int rowIndex = 0; foreach (DataRow row in dtSource.Rows) { #region 新建表,填充表頭,填充列頭,樣式 if (rowIndex == 65535 || rowIndex == 0) { if (rowIndex != 0) { sheet = workbook.CreateSheet(strSheetName + ((int)rowIndex / 65535).ToString()); } #region 列頭及樣式 { //HSSFRow headerRow = sheet.CreateRow(1); IRow headerRow = sheet.CreateRow(0); ICellStyle headStyle = workbook.CreateCellStyle(); headStyle.Alignment = HorizontalAlignment.Center; IFont font = workbook.CreateFont(); font.FontHeightInPoints = 10; font.Boldweight = 700; headStyle.SetFont(font); for (int i = 0; i < oldColumnNames.Length; i++) { headerRow.CreateCell(i).SetCellValue(newColumnNames[i]); headerRow.GetCell(i).CellStyle = headStyle; //設置列寬 sheet.SetColumnWidth(i, (arrColWidth[i] + 1) * 256); } /* foreach (DataColumn column in dtSource.Columns) { headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName); headerRow.GetCell(column.Ordinal).CellStyle = headStyle; //設置列寬 sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256); } * */ } #endregion rowIndex = 1; } #endregion #region 填充內容 IRow dataRow = sheet.CreateRow(rowIndex); //foreach (DataColumn column in dtSource.Columns) for (int i = 0; i < oldColumnNames.Length; i++) { ICell newCell = dataRow.CreateCell(i); string drValue = row[oldColumnNames[i]].ToString(); switch (dtSource.Columns[oldColumnNames[i]].DataType.ToString()) { case "System.String"://字符串類型 newCell.SetCellValue(drValue); break; case "System.DateTime"://日期類型 DateTime dateV; DateTime.TryParse(drValue, out dateV); newCell.SetCellValue(dateV); newCell.CellStyle = dateStyle;//格式化顯示 break; case "System.Boolean"://布爾型 bool boolV = false; bool.TryParse(drValue, out boolV); newCell.SetCellValue(boolV); break; case "System.Int16"://整型 case "System.Int32": case "System.Int64": case "System.Byte": int intV = 0; int.TryParse(drValue, out intV); newCell.SetCellValue(intV); break; case "System.Decimal"://浮點型 case "System.Double": double doubV = 0; double.TryParse(drValue, out doubV); newCell.SetCellValue(doubV); break; case "System.DBNull"://空值處理 newCell.SetCellValue(""); break; default: newCell.SetCellValue(""); break; } } #endregion rowIndex++; } using (MemoryStream ms = new MemoryStream()) { workbook.Write(ms); ms.Flush(); ms.Position = 0; //sheet.Dispose(); sheet = null; workbook = null; //workbook.Dispose();//通常只用寫這一個就OK了,他會遍歷並釋放全部資源,但當前版本有問題因此只釋放sheet getms= ms; } #endregion using (MemoryStream ms = getms) { using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write)) { byte[] data = ms.ToArray(); fs.Write(data, 0, data.Length); fs.Flush(); } } } /// <summary> /// DataTable導出到Excel的MemoryStream /// </summary> /// <param name="dtSource">源DataTable</param> /// <param name="strHeaderText">表頭文本</param> /// <param name="strSheetName">工做表名稱</param> /// <Author>CallmeYhz 2015-11-26 10:13:09</Author> public static MemoryStream Export(DataTable dtSource, string strHeaderText, string strSheetName, string[] oldColumnNames, string[] newColumnNames) { if (oldColumnNames.Length != newColumnNames.Length) { return new MemoryStream(); } HSSFWorkbook workbook = new HSSFWorkbook(); //HSSFSheet sheet = workbook.CreateSheet();// workbook.CreateSheet(); ISheet sheet = workbook.CreateSheet(strSheetName); #region 右擊文件 屬性信息 { DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation(); dsi.Company = "http://....../"; workbook.DocumentSummaryInformation = dsi; SummaryInformation si = PropertySetFactory.CreateSummaryInformation(); if (HttpContext.Current.Session["realname"] != null) { si.Author = HttpContext.Current.Session["realname"].ToString(); } else { if (HttpContext.Current.Session["username"] != null) { si.Author = HttpContext.Current.Session["username"].ToString(); } } //填加xls文件做者信息 si.ApplicationName = "NPOI"; //填加xls文件建立程序信息 si.LastAuthor = "OA系統"; //填加xls文件最後保存者信息 si.Comments = "OA系統自動建立文件"; //填加xls文件做者信息 si.Title = strHeaderText; //填加xls文件標題信息 si.Subject = strHeaderText; //填加文件主題信息 si.CreateDateTime = DateTime.Now; workbook.SummaryInformation = si; } #endregion ICellStyle dateStyle = workbook.CreateCellStyle(); IDataFormat format = workbook.CreateDataFormat(); dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd"); #region 取得列寬 int[] arrColWidth = new int[oldColumnNames.Length]; for (int i = 0; i < oldColumnNames.Length; i++) { arrColWidth[i] = Encoding.GetEncoding(936).GetBytes(newColumnNames[i]).Length; } /* foreach (DataColumn item in dtSource.Columns) { arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length; } * */ for (int i = 0; i < dtSource.Rows.Count; i++) { for (int j = 0; j < oldColumnNames.Length; j++) { int intTemp = Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][oldColumnNames[j]].ToString()).Length; if (intTemp > arrColWidth[j]) { arrColWidth[j] = intTemp; } } /* for (int j = 0; j < dtSource.Columns.Count; j++) { int intTemp = Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][j].ToString()).Length; if (intTemp > arrColWidth[j]) { arrColWidth[j] = intTemp; } } * */ } #endregion int rowIndex = 0; foreach (DataRow row in dtSource.Rows) { #region 新建表,填充表頭,填充列頭,樣式 if (rowIndex == 65535 || rowIndex == 0) { if (rowIndex != 0) { sheet = workbook.CreateSheet(strSheetName + ((int)rowIndex / 65535).ToString()); } #region 表頭及樣式 { IRow headerRow = sheet.CreateRow(0); headerRow.HeightInPoints = 25; headerRow.CreateCell(0).SetCellValue(strHeaderText); ICellStyle headStyle = workbook.CreateCellStyle(); headStyle.Alignment = HorizontalAlignment.Center; IFont font = workbook.CreateFont(); font.FontHeightInPoints = 20; font.Boldweight = 700; headStyle.SetFont(font); headerRow.GetCell(0).CellStyle = headStyle; //sheet.AddMergedRegion(new Region(0, 0, 0, dtSource.Columns.Count - 1)); sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, dtSource.Columns.Count - 1)); } #endregion #region 列頭及樣式 { //HSSFRow headerRow = sheet.CreateRow(1); IRow headerRow = sheet.CreateRow(1); ICellStyle headStyle = workbook.CreateCellStyle(); headStyle.Alignment = HorizontalAlignment.Center; IFont font = workbook.CreateFont(); font.FontHeightInPoints = 10; font.Boldweight = 700; headStyle.SetFont(font); for (int i = 0; i < oldColumnNames.Length; i++) { headerRow.CreateCell(i).SetCellValue(newColumnNames[i]); headerRow.GetCell(i).CellStyle = headStyle; //設置列寬 sheet.SetColumnWidth(i, (arrColWidth[i] + 1) * 256); } /* foreach (DataColumn column in dtSource.Columns) { headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName); headerRow.GetCell(column.Ordinal).CellStyle = headStyle; //設置列寬 sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256); } * */ } #endregion rowIndex = 2; } #endregion #region 填充內容 IRow dataRow = sheet.CreateRow(rowIndex); //foreach (DataColumn column in dtSource.Columns) for (int i = 0; i < oldColumnNames.Length; i++) { ICell newCell = dataRow.CreateCell(i); string drValue = row[oldColumnNames[i]].ToString(); switch (dtSource.Columns[oldColumnNames[i]].DataType.ToString()) { case "System.String"://字符串類型 newCell.SetCellValue(drValue); break; case "System.DateTime"://日期類型 DateTime dateV; DateTime.TryParse(drValue, out dateV); newCell.SetCellValue(dateV); newCell.CellStyle = dateStyle;//格式化顯示 break; case "System.Boolean"://布爾型 bool boolV = false; bool.TryParse(drValue, out boolV); newCell.SetCellValue(boolV); break; case "System.Int16"://整型 case "System.Int32": case "System.Int64": case "System.Byte": int intV = 0; int.TryParse(drValue, out intV); newCell.SetCellValue(intV); break; case "System.Decimal"://浮點型 case "System.Double": double doubV = 0; double.TryParse(drValue, out doubV); newCell.SetCellValue(doubV); break; case "System.DBNull"://空值處理 newCell.SetCellValue(""); break; default: newCell.SetCellValue(""); break; } } #endregion rowIndex++; } using (MemoryStream ms = new MemoryStream()) { workbook.Write(ms); ms.Flush(); ms.Position = 0; //sheet.Dispose(); sheet = null; workbook = null; //workbook.Dispose();//通常只用寫這一個就OK了,他會遍歷並釋放全部資源,但當前版本有問題因此只釋放sheet return ms; } } /// <summary> /// WEB導出DataTable到Excel /// </summary> /// <param name="dtSource">源DataTable</param> /// <param name="strHeaderText">表頭文本</param> /// <param name="strFileName">文件名</param> /// <Author>CallmeYhz 2015-11-26 10:13:09</Author> public static void ExportByWeb(DataTable dtSource, string strHeaderText, string strFileName) { ExportByWeb(dtSource, strHeaderText, strFileName, "sheet"); } /// <summary> /// WEB導出DataTable到Excel /// </summary> /// <param name="dtSource">源DataTable</param> /// <param name="strHeaderText">表頭文本</param> /// <param name="strFileName">輸出文件名,包含擴展名</param> /// <param name="oldColumnNames">要導出的DataTable列數組</param> /// <param name="newColumnNames">導出後的對應列名</param> public static void ExportByWeb(DataTable dtSource, string strHeaderText, string strFileName, string[] oldColumnNames, string[] newColumnNames) { ExportByWeb(dtSource, strHeaderText, strFileName, "sheet", oldColumnNames, newColumnNames); } /// <summary> /// WEB導出DataTable到Excel /// </summary> /// <param name="dtSource">源DataTable</param> /// <param name="strHeaderText">表頭文本</param> /// <param name="strFileName">輸出文件名</param> /// <param name="strSheetName">工做表名稱</param> public static void ExportByWeb(DataTable dtSource, string strHeaderText, string strFileName, string strSheetName) { HttpContext curContext = HttpContext.Current; // 設置編碼和附件格式 curContext.Response.ContentType = "application/vnd.ms-excel"; curContext.Response.ContentEncoding = Encoding.UTF8; curContext.Response.Charset = ""; curContext.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(strFileName, Encoding.UTF8)); //生成列 string columns = ""; for (int i = 0; i < dtSource.Columns.Count; i++) { if (i > 0) { columns += ","; } columns += dtSource.Columns[i].ColumnName; } curContext.Response.BinaryWrite(Export(dtSource, strHeaderText, strSheetName, columns.Split(','), columns.Split(',')).GetBuffer()); curContext.Response.End(); } /// <summary> /// 導出DataTable到Excel /// </summary> /// <param name="dtSource">要導出的DataTable</param> /// <param name="strHeaderText">標題文字</param> /// <param name="strFileName">文件名,包含擴展名</param> /// <param name="strSheetName">工做表名</param> /// <param name="oldColumnNames">要導出的DataTable列數組</param> /// <param name="newColumnNames">導出後的對應列名</param> public static void ExportByWeb(DataTable dtSource, string strHeaderText, string strFileName, string strSheetName, string[] oldColumnNames, string[] newColumnNames) { HttpContext curContext = HttpContext.Current; // 設置編碼和附件格式 curContext.Response.ContentType = "application/vnd.ms-excel"; curContext.Response.ContentEncoding = Encoding.UTF8; curContext.Response.Charset = ""; curContext.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(strFileName, Encoding.UTF8)); curContext.Response.BinaryWrite(Export(dtSource, strHeaderText, strSheetName, oldColumnNames, newColumnNames).GetBuffer()); curContext.Response.End(); } /// <summary>讀取excel /// 默認第一行爲表頭,導入第一個工做表 /// </summary> /// <param name="strFileName">excel文檔路徑</param> /// <returns></returns> public static DataTable Import(string strFileName) { DataTable dt = new DataTable(); HSSFWorkbook hssfworkbook; using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read)) { hssfworkbook = new HSSFWorkbook(file); } ISheet sheet = hssfworkbook.GetSheetAt(0); System.Collections.IEnumerator rows = sheet.GetRowEnumerator(); IRow headerRow = sheet.GetRow(0); int cellCount = headerRow.LastCellNum; for (int j = 0; j < cellCount; j++) { ICell cell = headerRow.GetCell(j); dt.Columns.Add(cell.ToString()); } for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++) { IRow row = sheet.GetRow(i); DataRow dataRow = dt.NewRow(); for (int j = row.FirstCellNum; j < cellCount; j++) { if (row.GetCell(j) != null) dataRow[j] = row.GetCell(j).ToString(); } dt.Rows.Add(dataRow); } return dt; } /// <summary> /// 從Excel中獲取數據到DataTable /// </summary> /// <param name="strFileName">Excel文件全路徑(服務器路徑)</param> /// <param name="SheetName">要獲取數據的工做表名稱</param> /// <param name="HeaderRowIndex">工做表標題行所在行號(從0開始)</param> /// <returns></returns> public static DataTable RenderDataTableFromExcel(string strFileName, string SheetName, int HeaderRowIndex) { using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read)) { IWorkbook workbook = new HSSFWorkbook(file); ISheet sheet = workbook.GetSheet(SheetName); return RenderDataTableFromExcel(workbook, SheetName, HeaderRowIndex); } } /// <summary> /// 從Excel中獲取數據到DataTable /// </summary> /// <param name="strFileName">Excel文件全路徑(服務器路徑)</param> /// <param name="SheetIndex">要獲取數據的工做表序號(從0開始)</param> /// <param name="HeaderRowIndex">工做表標題行所在行號(從0開始)</param> /// <returns></returns> public static DataTable RenderDataTableFromExcel(string strFileName, int SheetIndex, int HeaderRowIndex) { using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read)) { IWorkbook workbook = new HSSFWorkbook(file); string SheetName = workbook.GetSheetName(SheetIndex); return RenderDataTableFromExcel(workbook, SheetName, HeaderRowIndex); } } /// <summary> /// 從Excel中獲取數據到DataTable /// </summary> /// <param name="ExcelFileStream">Excel文件流</param> /// <param name="SheetName">要獲取數據的工做表名稱</param> /// <param name="HeaderRowIndex">工做表標題行所在行號(從0開始)</param> /// <returns></returns> public static DataTable RenderDataTableFromExcel(Stream ExcelFileStream, string SheetName, int HeaderRowIndex) { IWorkbook workbook = new HSSFWorkbook(ExcelFileStream); ExcelFileStream.Close(); return RenderDataTableFromExcel(workbook, SheetName, HeaderRowIndex); } /// <summary> /// 從Excel中獲取數據到DataTable /// </summary> /// <param name="ExcelFileStream">Excel文件流</param> /// <param name="SheetIndex">要獲取數據的工做表序號(從0開始)</param> /// <param name="HeaderRowIndex">工做表標題行所在行號(從0開始)</param> /// <returns></returns> public static DataTable RenderDataTableFromExcel(Stream ExcelFileStream, int SheetIndex, int HeaderRowIndex) { IWorkbook workbook = new HSSFWorkbook(ExcelFileStream); ExcelFileStream.Close(); string SheetName = workbook.GetSheetName(SheetIndex); return RenderDataTableFromExcel(workbook, SheetName, HeaderRowIndex); } /// <summary> /// 從Excel中獲取數據到DataTable /// </summary> /// <param name="workbook">要處理的工做薄</param> /// <param name="SheetName">要獲取數據的工做表名稱</param> /// <param name="HeaderRowIndex">工做表標題行所在行號(從0開始)</param> /// <returns></returns> public static DataTable RenderDataTableFromExcel(IWorkbook workbook, string SheetName, int HeaderRowIndex) { ISheet sheet = workbook.GetSheet(SheetName); DataTable table = new DataTable(); try { IRow headerRow = sheet.GetRow(HeaderRowIndex); int cellCount = headerRow.LastCellNum; for (int i = headerRow.FirstCellNum; i < cellCount; i++) { DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue); table.Columns.Add(column); } int rowCount = sheet.LastRowNum; #region 循環各行各列,寫入數據到DataTable for (int i = (sheet.FirstRowNum + 1); i <=sheet.LastRowNum; i++) { IRow row = sheet.GetRow(i); DataRow dataRow = table.NewRow(); for (int j = row.FirstCellNum; j < cellCount; j++) { ICell cell = row.GetCell(j); if (cell == null) { dataRow[j] = null; } else { //dataRow[j] = cell.ToString(); switch (cell.CellType) { case CellType.Blank: dataRow[j] = null; break; case CellType.Boolean: dataRow[j] = cell.BooleanCellValue; break; case CellType.Numeric: dataRow[j] = cell.ToString(); break; case CellType.String: dataRow[j] = cell.StringCellValue; break; case CellType.Error: dataRow[j] = cell.ErrorCellValue; break; case CellType.Formula: default: dataRow[j] = "=" + cell.CellFormula; break; } } } table.Rows.Add(dataRow); //dataRow[j] = row.GetCell(j).ToString(); } #endregion } catch (System.Exception ex) { table.Clear(); table.Columns.Clear(); table.Columns.Add("出錯了"); DataRow dr = table.NewRow(); dr[0] = ex.Message; table.Rows.Add(dr); return table; } finally { //sheet.Dispose(); workbook = null; sheet = null; } #region 清除最後的空行 for (int i = table.Rows.Count - 1; i > 0; i--) { bool isnull = true; for (int j = 0; j < table.Columns.Count; j++) { if (table.Rows[i][j] != null) { if (table.Rows[i][j].ToString() != "") { isnull = false; break; } } } if (isnull) { table.Rows[i].Delete(); } } #endregion return table; } } }
爲了讓本身印象深入,設計了一個前端頁面僅供參考數組
<html> <head> <title> ASP.MVC+Bootstrap+NPOI </title> <script src="~/Scripts/jquery-2.1.4.min.js"></script> <link href="~/Content/bootstrap.min.css" rel="stylesheet" /> <script src="~/Scripts/bootstrap.min.js"></script> <style> .container { padding: 20px 0; } </style> </head> <body> <div class="container"> <form class="form-horizontal" action="Upload" role="form" method="post" enctype="multipart/form-data"> <div class="form-group"> <div class="col-md-3"> <label class="control-label" style="float:right">上傳文件</label> </div> <div class="col-md-3"> <input id="fileUpload" name="fileUpload" type="file" style="display:none" /> <input id="fileText" type="text" class="form-control" disabled /> </div> <div class="col-md-0"> <button type="button" class=" btn btn-primary" onclick="$('#fileUpload').click()">瀏覽</button> </div> </div> <script> $("#fileUpload").change(function () { $("#fileText").val($(this).val()); }) </script> <div class="form-group"> <div class="col-md-3 col-md-offset-3"> <button type="submit" class=" btn btn-primary">導入</button> <div class="btn-group"> <div class="btn-group"> <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown"> 導出模板 </button> <ul class="dropdown-menu" role="menu"> <li><a href="GetExportExcelUrl?ExportTypeIndex=1">導出到.csv</a></li> <li><a href="GetExportExcelUrl?ExportTypeIndex=2">導出到.xls</a></li> <li><a href="GetExportExcelUrl?ExportTypeIndex=3">導出到.xlsx</a></li> </ul> </div> </div> </div> </div> </form> </div> </body> </html>
導入支持.csv、.xls、.xlsx三種格式讀出數據到DataTable,接下來能夠進行一系列操做服務器
/// <summary> /// 說明:導入的方法 /// 做者:CallmeYhz /// 時間:2015-11-26 14:23:15 /// </summary> /// <param name="fileUpload"></param> /// <returns></returns> public string Upload(HttpPostedFileBase fileUpload) { if (fileUpload == null) { return "文件爲空"; } try { //將硬盤路徑轉化爲服務器路徑的文件流 string fileName = Path.Combine(Request.MapPath("~/SaveFile"), Path.GetFileName(fileUpload.FileName)); //NPOI獲得EXCEL的第一種方法 fileUpload.SaveAs(fileName); DataTable dtData = ExcelHelper.Import(fileName); //獲得EXCEL的第二種方法(第一個參數是文件流,第二個是excel標籤名,第三個是第幾行開始讀0算第一行) DataTable dtData2 = ExcelHelper.RenderDataTableFromExcel(fileName, "Sheet", 0); return "導入成功"; } catch { return "導入失敗"; } }
第一種方法是默認文件的第一行是列名,第二行是數據。第二種方法能夠指定標籤,行頭等參數。網絡
思路是用NPOI建立文件存放在服務器上而後返回URL開始下載,藉助一些方法能夠方便進行如下操做架構
利用反射得到實體的全部屬性(一個表的全部列):app
/// <summary> /// 說明:得到一個對象的全部屬性 /// </summary> /// <returns></returns> private string[] GetPropertyNameArray() { PropertyInfo[] props = null; try { Type type = typeof(Student); object obj = Activator.CreateInstance(type); props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); string[] array = props.Select(t => t.Name).ToArray(); return array; } catch (Exception ex) { return null; } }
將List集合轉化成DataTable:
/// <summary> /// 將泛類型集合List類轉換成DataTable /// </summary> /// <param name="list">泛類型集合</param> /// <returns></returns> public DataTable ListToDataTable<T>(List<T> entitys) { //檢查實體集合不能爲空 if (entitys == null || entitys.Count < 1) { throw new Exception("需轉換的集合爲空"); } //取出第一個實體的全部Propertie Type entityType = entitys[0].GetType(); PropertyInfo[] entityProperties = entityType.GetProperties(); //生成DataTable的structure //生產代碼中,應將生成的DataTable結構Cache起來,此處略 DataTable dt = new DataTable(); for (int i = 0; i < entityProperties.Length; i++) { //dt.Columns.Add(entityProperties[i].Name, entityProperties[i].PropertyType); dt.Columns.Add(entityProperties[i].Name); } //將全部entity添加到DataTable中 foreach (object entity in entitys) { //檢查全部的的實體都爲同一類型 if (entity.GetType() != entityType) { throw new Exception("要轉換的集合元素類型不一致"); } object[] entityValues = new object[entityProperties.Length]; for (int i = 0; i < entityProperties.Length; i++) { entityValues[i] = entityProperties[i].GetValue(entity, null); } dt.Rows.Add(entityValues); } return dt; }
導出:
/// <summary> /// 得到導出的url並導出 /// </summary> /// <param name="ExportTypeIndex">導出EXCEL類型索引</param> /// <returns>URL提供用戶下載</returns> public FileResult GetExportExcelUrl(int ExportTypeIndex) { //構造導出的集合 List<Student> StudentList = new List<Student>() { new Student() { SnoID="1", SAge=25, SName="yhz", SDateTime=DateTime.Now }, new Student() { SnoID="2", SAge=26, SName="kq", SDateTime=DateTime.Now } }; string[] oldColumn = GetPropertyNameArray(); string[] newColumn = new string[] { "學號", "姓名", "年齡", "如今時間" }; //類型轉換(將List轉化爲DataTable) DataTable ExportDt = this.ListToDataTable<Student>(StudentList); //能夠考慮讀取配置文件 string path = "/SaveFile/"; string fileName = ""; if(ExportTypeIndex==1) { fileName = "導出CSV.csv"; } else if (ExportTypeIndex == 2) { fileName = "導出XLS.xls"; } else { fileName = "導出XLSX.xlsx"; } string streamFileName = Path.Combine(Request.MapPath(path), Path.GetFileName(fileName)); //調用改寫的NPOI方法 ExcelHelper.MyExport(ExportDt, "你們好我是表頭",streamFileName, "1", oldColumn, newColumn); if (ExportTypeIndex == 1) { return File(path + fileName, "application/zip-x-compressed", "物流訂單模板導出.csv"); } else if (ExportTypeIndex == 2) { return new FilePathResult(path + fileName, "application/vnd.ms-excel"); } else { return new FilePathResult(path+fileName, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet "); } }
http://files.cnblogs.com/files/CallmeYhz/MVCForNPOI.rar
簡單的導出EXCEL方法:
public ActionResult Export() { string table = "<table border='1px solid black'><tr><td>編號</td><td>真實姓名</td><td>暱稱</td><td>電話</td><td>數量</td><td>參與時間</td><td>狀態</td><td>備註</td></tr>"; table += "<tr><td>1</td><td>2</td><td>3</td><td>4<td>5</td><td>6</td><td>6</td><td>6</td></tr>"; table += "</table>"; string fileName = "用戶列表" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".xls"; Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName); Response.ContentType = "application/excel"; Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); Response.Write(table); Response.End(); return View(); }