下載:
http://pan.baidu.com/s/1boTpT5l
使用方法:
導入:
使用 ReadToDataTable方法
導出:
NPOIExcel.ExcelManager manger1 = new ExcelManager(this.textBox2.Text, ExcelManager.DealType.exportExcel); manger1.SetDataSource(dt, 1); //設置標題行 manger1.SetRangeStyle("A1", "D1") .SetCellMerge() .SetFontColor(NPOIStyle.NPOIColor.Blue) .SetBackgroundColor(NPOIStyle.NPOIColor.Yellow) .SetFontBold() .SetFontItalic() .SetFontSize(18) .SetCellText("2016 這里是標題") .SetEnd(); // 設置數據 manger1.SetRangeStyle("a2", "d5") .SetFontName("微軟雅黑") .SetFontSize(12) .SetHorizontalAlignment(NPOIStyle.Alignment.Left) .SetBorderAll() .SetEnd(); //設置尾行 manger1.SetRangeStyle("e8", "f9") .SetCellMerge() .SetFontColor(NPOIStyle.NPOIColor.Red) .SetFontItalic() .SetFontSize(14) .SetCellText("2016 簽名") .SetBorderBottom() .SetBorderRight() .SetEnd(); //導出文件 manger1.ExportExcelFile();
源碼:
using System; using System.Collections.Generic; using System.Text; using System.Data; using NPOI.SS.UserModel; using System.IO; using NPOI.XSSF.UserModel; using NPOI.SS.Util; using NPOI.HSSF.Util; namespace NPOIExcel { public class Point { public int X { get; set; } public int Y { get; set; } } public class Range { public int FIRSTROW { get; set; } public int LASTROW { get; set; } public int FIRSTCOL { get; set; } public int LASTCOL { get; set; } } public class ExcelManager { #region 屬性 private string inPutPath { get; set; } private string outPutPath { get; set; } private IWorkbook workbook { get; set; } private ISheet sheet { get; set; } #endregion #region 初始化 //public ExcelManager() { } /// <summary> /// 創建一個用於導入,導出 數據的管理類 /// </summary> /// <param name="Path">文件路徑</param> /// <param name="type">設置路徑為導入或導出</param> public ExcelManager(string Path, DealType type) { //設置導入文件的路徑,workBook if (type == DealType.importExcel) { inPutPath = Path; using (FileStream file = new FileStream(inPutPath, FileMode.Open, FileAccess.Read)) { workbook = WorkbookFactory.Create(file); } } if (type == DealType.exportExcel) { outPutPath = Path; workbook = new XSSFWorkbook(); sheet = workbook.CreateSheet("sheet1"); } } /// <summary> /// 對Excel的操作類型 /// </summary> public enum DealType { importExcel, exportExcel } #endregion #region "基礎樣式設置---2016-05-17 fengylc add " /// <summary> /// 設置范圍內的樣式 /// </summary> /// <param name="startPoint">開始的單元格:例-A1</param> /// <param name="endPoint">結束的單元格:例-B1</param> /// <returns>樣式</returns> public NPOIStyle SetRangeStyle(string startPoint, string endPoint) { return new NPOIStyle(workbook, sheet, startPoint, endPoint); } #endregion #region 導入 /// <summary> /// 讀取Excel到DataTable,默認第一行為列名 /// </summary> /// <param name="headRowCount">表頭的行數,從表頭下一行開始是數據</param> /// <returns>DataTable</returns> public DataTable ReadExcelToDataTable(int headRowCount = 1) { using (FileStream file = new FileStream(inPutPath, FileMode.Open, FileAccess.Read)) { workbook = WorkbookFactory.Create(file); } sheet = workbook.GetSheetAt(0); DataTable dtl = new DataTable(sheet.SheetName.Trim()); IRow headRow = sheet.GetRow(0); int columnCount = headRow.Cells.Count; for (int index = 0; index <= columnCount - 1; index++) { if (headRow.Cells[index].Equals(null)) dtl.Columns.Add(string.Empty, typeof (string)); else { if(CellType.Numeric==headRow.Cells[index].CellType) dtl.Columns.Add(headRow.Cells[index].NumericCellValue.ToString().Trim(), typeof(string)); else dtl.Columns.Add(headRow.Cells[index].StringCellValue.Trim(), typeof(string)); } } for (int x = headRowCount; x <= sheet.LastRowNum; x++) { IRow contentRow = sheet.GetRow(x); if (contentRow.Equals(null)) continue; else { DataRow dr = dtl.NewRow(); bool isEmpty = true; for (int y = 0; y <= columnCount - 1; y++) { if (contentRow.GetCell(y).Equals(null)) { dr[y] = string.Empty; } else { ICell contentCell = contentRow.GetCell(y); switch (contentCell.CellType) { case CellType.Blank: dr[y] = string.Empty; break; case CellType.Boolean: break; case CellType.Error: break; case CellType.Formula: dr[y] = contentCell.StringCellValue.Trim(); break; case CellType.Numeric: { if (DateUtil.IsCellDateFormatted(contentCell)) dr[y] = contentCell.DateCellValue.ToString("yyyy-MM-dd HH:mm:ss"); else dr[y] = contentCell.NumericCellValue.ToString().Trim(); } break; case CellType.String: dr[y] = contentCell.StringCellValue.Trim(); break; case CellType.Unknown: break; } isEmpty = string.IsNullOrEmpty(dr[y].ToString().Trim()) && isEmpty; } } //非全空添加行 if (!isEmpty) dtl.Rows.Add(dr); } } return dtl; } #endregion #region 導出 /// <summary> /// 設置數據源 /// </summary> /// <param name="dt">數據</param> /// <param name="headEmptyLineCount">最上方留出的空行</param> public void SetDataSource(DataTable dt, int headEmptyLineCount = 0) { try { int TotalNum = dt.Rows.Count + headEmptyLineCount + 1;// (加上 空行 ) //添加數據 addData(TotalNum, headEmptyLineCount + 1, sheet, dt); //標題設置 for (int i = 0; i < dt.Columns.Count; i++) { sheet.GetRow(headEmptyLineCount).GetCell(i).SetCellValue(dt.Columns[i].ColumnName); } } catch (Exception ex) { throw ex; } } /// <summary> /// 導出文件 /// </summary> /// <param name="fileName">文件名,不指定為隨機生成</param> public void ExportExcelFile(string fileName = "") { Random ran = new Random(); if (string.IsNullOrEmpty(fileName)) { fileName = "\\" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ran.Next(1000, 9999).ToString() + ".xlsx"; } else { fileName = "\\" + fileName + ".xlsx"; } string CreatePath = outPutPath + fileName; FileStream NewFile = new FileStream(CreatePath, FileMode.Create); workbook.Write(NewFile); } private static void addData(int TotalNum, int headCount, ISheet sheet, DataTable dt) { //添加數據 for (int i = 0; i < TotalNum; i++) { IRow row = sheet.CreateRow(i); for (int j = 0; j < dt.Columns.Count; j++) { row.CreateCell(j); if (i >= headCount) { try { double cellData = double.Parse(dt.Rows[i - headCount][j].ToString()); row.CreateCell(j).SetCellValue(cellData); } catch { string cellData = dt.Rows[i - headCount][j].ToString(); if (cellData.Trim().Length > 1 && cellData.Substring(0, 1) == "'") { cellData = cellData.Substring(1, cellData.Length - 1); } row.CreateCell(j).SetCellValue(cellData); } } } } } #endregion } /// <summary> /// 設置樣式 /// </summary> public class NPOIStyle { public Range range { get; set; } public ISheet sheet { get; set; } public ICellStyle cellStyle { get; set; } public IFont cellFontStyle { get; set; } public NPOIStyle(IWorkbook workbook, ISheet sheet, string startPoint, string endPoint) { cellStyle = workbook.CreateCellStyle(); cellFontStyle = workbook.CreateFont(); this.sheet = sheet; range = GetRange(startPoint, endPoint); } public enum Alignment { Center, Fill, Left, Right, Bottom, Top } public enum NPOIColor : short { Black = 8, Brown = 60, OliveGreen = 59, DarkGreen = 58, DarkTeal = 56, DarkBlue = 18, Indigo = 62, Grey80Percent = 63, DarkRed = 16, Orange = 53, DarkYellow = 19, Green = 17, Teal = 21, Blue = 12, BlueGrey = 54, Grey50Percent = 23, Red = 10, LightOrange = 52, Lime = 50, SeaGreen = 57, Aqua = 49, LightBlue = 48, Violet = 20, Grey40Percent = 55, Pink = 14, Gold = 51, Yellow = 13, BrightGreen = 11, Turquoise = 15, SkyBlue = 40, Plum = 61, Grey25Percent = 22, Rose = 45, Tan = 47, LightYellow = 43, LightGreen = 42, LightTurquoise = 41, PaleBlue = 44, Lavender = 46, White = 9, CornflowerBlue = 24, LemonChiffon = 26, Maroon = 25, Orchid = 28, Coral = 29, RoyalBlue = 30, LightCornflowerBlue = 31, Automatic = 64 } /// <summary> /// 把Excel列名字母轉換為 數字坐標 /// </summary> /// <param name="character">Excel列名</param> /// <returns>轉換后的數字</returns> public static int Asc(string character) { character = character.ToUpper(); char[] arry = character.ToCharArray(); int total = 0; for (int i = 0; i < character.Length; i++) { total += (Convert.ToInt32(arry[i]) - 65) + 26 * i; } return total; } /// <summary> /// 把‘A1’類型轉換成Point類型 /// </summary> /// <param name="point">字符點</param> /// <returns>Point</returns> public static Point GetPoint(string point) { Point newPoint = new Point(); char[] arry = point.ToCharArray(); int index = 0; for (int i = 0; i < point.Length; i++) { if (Char.IsNumber(arry[i])) { index = i; break; } } newPoint.Y = Asc(point.Substring(0, index)); newPoint.X = int.Parse(point.Substring(index, point.Length - index)) - 1; return newPoint; } /// <summary> /// 根據兩個點確定一個范圍 /// </summary> /// <param name="startPosition">Excel上的開始點</param> /// <param name="endPosition">Excel上的結束點</param> /// <returns>范圍</returns> public Range GetRange(string startPosition, string endPosition) { Range range = new Range(); Point start = GetPoint(startPosition); Point end = GetPoint(endPosition); range.FIRSTROW = start.X; range.LASTROW = end.X; range.FIRSTCOL = start.Y; range.LASTCOL = end.Y; for (int row = range.FIRSTROW; row <= range.LASTROW; row++) { if (sheet.GetRow(row) == null) sheet.CreateRow(row); for (int col = range.FIRSTCOL; col <= range.LASTCOL; col++) { if (sheet.GetRow(row).GetCell(col) == null) sheet.GetRow(row).CreateCell(col); } } return range; } /// <summary> /// 設置樣式的必要設置:設置樣式的范圍 /// </summary> /// <param name="startPoint">范圍起始點</param> /// <param name="endPoint">范圍結束點</param> /// <returns>設置樣式的范圍</returns> public NPOIStyle SetRange(string startPoint, string endPoint) { this.range = GetRange(startPoint, endPoint); return this; } /// <summary> /// 合並單元格 /// </summary> /// <param name="startPosition">合並開始的單元格</param> /// <param name="endPosition">合並結束的單元格</param> /// <returns></returns> public NPOIStyle SetCellMerge() { //把excel單元格帶字母坐標 轉換為 數字坐標 CellRangeAddress cellRangeAddress = new CellRangeAddress(range.FIRSTROW, range.LASTROW, range.FIRSTCOL, range.LASTCOL); this.sheet.AddMergedRegion(cellRangeAddress); return this; } /// <summary> /// 設置字體大小 /// </summary> /// <param name="size">字體大小:9,10,11...</param> /// <returns>Manager</returns> public NPOIStyle SetFontSize(short size) { cellFontStyle.FontHeightInPoints = size; return this; } /// <summary> /// 設置sheet頁面上列的寬 /// </summary> /// <param name="size"></param> /// <returns></returns> public NPOIStyle SetSheetColumnWidthSize(short size) { sheet.DefaultColumnWidth = size; return this; } /// <summary> /// 設置字體樣式 /// </summary> /// <param name="FontName">字體:宋體,黑體...</param> /// <returns>Manager</returns> public NPOIStyle SetFontName(string FontName) { cellFontStyle.FontName = FontName; return this; } /// <summary> /// 設置字體加粗 /// </summary> /// <returns>Manager</returns> public NPOIStyle SetFontBold() { cellFontStyle.Boldweight = (short)FontBoldWeight.Bold; return this; } /// <summary> /// 設置字體下划線 /// </summary> /// <returns>Manager</returns> public NPOIStyle SetFontUnderline() { cellFontStyle.Underline = FontUnderlineType.Single; return this; } /// <summary> /// 設置字體下傾斜 /// </summary> /// <returns>Manager</returns> public NPOIStyle SetFontItalic() { cellFontStyle.IsItalic = true; return this; } /// <summary> /// 設置字體水平對齊 /// </summary> /// <returns>Manager</returns> public NPOIStyle SetHorizontalAlignment(Alignment alignment) { switch (alignment) { case Alignment.Center: cellStyle.Alignment = HorizontalAlignment.Center; break; case Alignment.Fill: cellStyle.Alignment = HorizontalAlignment.Fill; break; case Alignment.Left: cellStyle.Alignment = HorizontalAlignment.Left; break; case Alignment.Right: cellStyle.Alignment = HorizontalAlignment.Right; break; default: break; } return this; } /// <summary> /// 設置字體垂直對齊 /// </summary> /// <returns>Manager</returns> public NPOIStyle SetVerticalAlignment(Alignment alignment) { switch (alignment) { case Alignment.Center: cellStyle.VerticalAlignment = VerticalAlignment.Center; break; case Alignment.Fill: cellStyle.VerticalAlignment = VerticalAlignment.Justify; break; case Alignment.Top: cellStyle.VerticalAlignment = VerticalAlignment.Top; break; case Alignment.Bottom: cellStyle.VerticalAlignment = VerticalAlignment.Bottom; break; default: break; } return this; } /// <summary> /// 設置字體顏色 /// </summary> /// <param name="FontName">字體:宋體,黑體...</param> /// <returns>Manager</returns> public NPOIStyle SetFontColor(NPOIColor color) { cellFontStyle.Color = (short)color; return this; } /// <summary> /// 設置單元格背景色 /// </summary> /// <param name="color"></param> /// <returns></returns> public NPOIStyle SetBackgroundColor(NPOIColor color) { cellStyle.FillPattern = FillPattern.SolidForeground; cellStyle.FillForegroundColor = (short)color; return this; } /// <summary> /// 設置單元格的文字 /// </summary> /// <param name="position"></param> /// <param name="text"></param> public NPOIStyle SetCellText(string text) { sheet.GetRow(range.FIRSTROW).GetCell(range.FIRSTCOL).SetCellValue(text); return this; } /// <summary> /// 設置邊框(Range內每個單元格的四邊) /// </summary> /// <returns></returns> public NPOIStyle SetBorderAll() { cellStyle.BorderBottom = BorderStyle.Thin; cellStyle.BorderLeft = BorderStyle.Thin; cellStyle.BorderRight = BorderStyle.Thin; cellStyle.BorderTop = BorderStyle.Thin; return this; } public NPOIStyle SetBorderBottom() { cellStyle.BorderBottom = BorderStyle.Thin; return this; } public NPOIStyle SetBorderLeft() { cellStyle.BorderLeft = BorderStyle.Thin; return this; } public NPOIStyle SetBorderRight() { cellStyle.BorderRight = BorderStyle.Thin; return this; } public NPOIStyle SetBorderTop() { cellStyle.BorderTop = BorderStyle.Thin; return this; } /// <summary> /// 樣式設置結束,調用此方法生效 /// </summary> public void SetEnd() { for (int i = range.FIRSTROW; i <= range.LASTROW; i++) { for (int j = range.FIRSTCOL; j <= range.LASTCOL; j++) { cellStyle.SetFont(cellFontStyle); sheet.GetRow(i).GetCell(j).CellStyle = cellStyle; } } } } }