NPOI能夠在沒有安裝Office的狀況下對Word或Excel文檔進行讀寫操做瀏覽器
下面介紹下NPOI操做Excel的方法服務器
首先咱們須要下載NPOI的程序集 app
下載地址 http://npoi.codeplex.com/releasesthis
我下載下來是有這兩個文件spa
這裏使用的是net4.0excel
將下面幾個dll添加到項目中並引用code
廢話很少說 上代碼orm
/// <summary> /// create 2016-11-30 by sly /// 將DataTable數據導入到excel中 此方法直接返回文件給瀏覽器下載 /// </summary> /// <param name="data">要導入的數據</param> /// <param name="isColumnWritten">DataTable的列名是否要導入</param> /// <param name="sheetName">要導入的excel的sheet的名稱</param> /// <param name="widthDic">要設置的寬度(key 列下標,val 寬度大小)</param> /// <returns></returns> public int DataTableToExcel(DataTable data, string sheetName, bool isColumnWritten, Dictionary<int, int> widthDic = null) { int i = 0; int j = 0; int count = 0; ISheet sheet = null; MemoryStream file = new MemoryStream(); if (fileName.IndexOf(".xlsx") > 0) //2007版本 workbook = new XSSFWorkbook(); else if (fileName.IndexOf(".xls") > 0) // 2003版本 workbook = new HSSFWorkbook(); try { if (workbook != null) { sheet = workbook.CreateSheet(sheetName); //設置全部列寬 for (int l = 0; l <= data.Rows.Count; l++) { sheet.DefaultColumnWidth = 12; } if (widthDic != null) { //設定自定義寬度 foreach (var item in widthDic) { sheet.SetColumnWidth(item.Key, item.Value); } } } else { return -1; } if (isColumnWritten == true) //寫入DataTable的列名 { IRow row = sheet.CreateRow(0); for (j = 0; j < data.Columns.Count; ++j) { row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName); } count = 1; } else { count = 0; } int outRes = -1; for (i = 0; i < data.Rows.Count; ++i) { IRow row = sheet.CreateRow(count); for (j = 0; j < data.Columns.Count; ++j) { if (int.TryParse(data.Rows[i][j].ToString(), out outRes)) { row.CreateCell(j).SetCellValue(Convert.ToInt32(data.Rows[i][j].ToString())); } else { if (!string.IsNullOrEmpty(data.Rows[i][j].ToString()) && data.Rows[i][j].ToString().Length > 10) { if ((data.Rows[i][j].ToString().Substring(0, 7) == "http://" || data.Rows[i][j].ToString().Substring(0, 8) == "https://")) { var TCell = row.CreateCell(j); HSSFHyperlink link = new HSSFHyperlink(HyperlinkType.Url);//建一個HSSFHyperlink實體,指明連接類型爲URL TCell.SetCellValue(data.Rows[i][j].ToString()); link.Address = data.Rows[i][j].ToString();//給HSSFHyperlink的地址賦值 TCell.Hyperlink = link; } else { row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString()); } } else { row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString()); } } } ++count; } workbook.Write(file); //寫入到excel var context = System.Web.HttpContext.Current; context.Response.ContentType = "application/vnd.ms-excel"; context.Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", fileName)); context.Response.Clear(); context.Response.BinaryWrite(file.GetBuffer()); context.Response.End(); return count; } catch (Exception ex) { return -2; } }
/// <summary> /// 將excel中的數據導入到DataTable中 /// </summary> /// <param name="sheetName">excel工做薄sheet的名稱</param> /// <param name="isFirstRowColumn">第一行是不是DataTable的列名</param> /// <returns></returns> public DataTable ExcelToDataTable(string sheetName, bool isFirstRowColumn) { ISheet sheet = null; DataTable data = new DataTable(); int startRow = 0; try { fs = new FileStream(fileName, FileMode.Open, FileAccess.Read); if (fileName.IndexOf(".xlsx") > 0) // 2007版本 workbook = new XSSFWorkbook(fs); else if (fileName.IndexOf(".xls") > 0) // 2003版本 workbook = new HSSFWorkbook(fs); if (sheetName != null) { sheet = workbook.GetSheet(sheetName); if (sheet == null) //若是沒有找到指定的sheetName對應的sheet,則嘗試獲取第一個sheet { sheet = workbook.GetSheetAt(0); } } else { sheet = workbook.GetSheetAt(0); } if (sheet != null) { IRow firstRow = sheet.GetRow(0); int cellCount = firstRow.LastCellNum; //一行最後一個cell的編號 即總的列數 if (isFirstRowColumn) { for (int i = firstRow.FirstCellNum; i < cellCount; ++i) { ICell cell = firstRow.GetCell(i); if (cell != null) { string cellValue = cell.StringCellValue; if (cellValue != null) { DataColumn column = new DataColumn(cellValue); data.Columns.Add(column); } } } startRow = sheet.FirstRowNum + 1; } else { startRow = sheet.FirstRowNum; } //最後一列的標號 int rowCount = sheet.LastRowNum; for (int i = startRow; i <= rowCount; ++i) { IRow row = sheet.GetRow(i); if (row == null) continue; //沒有數據的行默認是null DataRow dataRow = data.NewRow(); for (int j = row.FirstCellNum; j < cellCount; ++j) { if (row.GetCell(j) != null) //同理,沒有數據的單元格都默認是null dataRow[j] = row.GetCell(j).ToString(); } data.Rows.Add(dataRow); } } return data; } catch (Exception ex) { return null; } }
/// <summary> /// 合併單元格 /// </summary> /// <param name="sheet">要合併單元格所在的sheet</param> /// <param name="rowstart">開始行的索引</param> /// <param name="rowend">結束行的索引</param> /// <param name="colstart">開始列的索引</param> /// <param name="colend">結束列的索引</param> public static void SetCellRangeAddress(ISheet sheet, int rowstart, int rowend, int colstart, int colend) { CellRangeAddress cellRangeAddress = new CellRangeAddress(rowstart, rowend, colstart, colend); sheet.AddMergedRegion(cellRangeAddress); }
//調用導出方法 new Helper.ExcelHelper("導出的文件名.xls").DataTableToExcel(dt, "sheet1", true, null); new Helper.ExcelHelper("導出的文件名.xlsx").DataTableToExcel(dt, "sheet1", true, null);
下面是導入blog
<input type="file" name="fileField" class="file" id="fileField" value="導入" style="display: none;" /> <script> $("#fileField").live("change", function () { var Reg = new RegExp("^.+\.(xls)"); var Reg2 = new RegExp("^.+\.(xlsx)"); if (Reg.test($(this).val()) || Reg.test2($(this).val())) { ImportGrade();//此處調用後臺導入方法,這裏就不寫了哈 } else { $.IvanDialogOpen({ "Type": "tips", "Info": "僅支持 .xls ,.xlsx 文件", "Plugins": { CloseTime: 800 } }); } }) </script>
/// <summary> /// 導入Demo /// </summary> /// <param name="filePath"></param> /// <returns></returns> public ActionResult ImportGrade(string filePath) { //獲取文件在服務器上的路徑 string path = string.Concat(FileUpload.GetFilePath(UploadType.ImportGradeFile), filePath); //根據上傳路徑獲取表格數據 ExcelHelper eh = new ExcelHelper(path.Replace("\\", "/")); DataTable dt = eh.ExcelToDataTable("Sheet1", true); return Content(""); }
以上就是NPOI的簡單使用方法索引