using System; using System.Data; using System.Data.OleDb; using GThinking.N_MISPROAS; using NPOI.HSSF.UserModel; using System.IO; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using NPOI.SS.Util; using System.Text.RegularExpressions; using System.Collections.Generic; using NPOI.HSSF.Util; namespace GThinking.N_MISPRO.Data { /// /// Excel转DataSet类 /// public class TExcelData : IDisposable { private string m_path; private OleDbConnection m_conn; private bool m_hasHeaderRow; private bool m_delfile; private static bool bOLEDB = true; /// /// 构造函数。 /// /// 要打开的EXCEL文件。 public TExcelData(string path, bool delfile) { m_path = path; m_hasHeaderRow = true; m_delfile = delfile; } /// /// 构造函数。 /// /// 要打开的EXCEL文件。 /// Excel第一行是否是标题行。 public TExcelData(string path, bool hasHeaderRow, bool delfile) { m_path = path; m_hasHeaderRow = hasHeaderRow; m_delfile = delfile; } public virtual void Close() { this.Dispose(true); GC.SuppressFinalize(this); } public void Dispose() { this.Close(); } protected virtual void Dispose(bool disposing) { if (m_conn == null) return; if (m_conn.State == ConnectionState.Open) { m_conn.Dispose(); m_conn = null; } if (m_delfile) { if (System.IO.File.Exists(m_path)) System.IO.File.Delete(m_path); } } ~TExcelData() { if (this.m_conn != null) { this.Dispose(false); } } // 根据32/64位运行时返回不同的连接字符串。 private string GetConnString() { string conn; if (AppRuntime.BitType == AppBitType.Bit32) { // 以文本类型读取混合类型列。Jet.OLEDB提供程序将返回前8行占多数的类型的数据,对于占少数的数据类型,则会返回 NULL(空)值。如果该列中两种类型数据的数量相等,将优先选择数字型数据,放弃文本型数据。 if (m_hasHeaderRow) conn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + m_path + @";Extended Properties=""Excel 8.0;IMEX=1;ImportMixedTypes=Text;"";"; else conn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + m_path + @";Extended Properties=""Excel 8.0;IMEX=1;ImportMixedTypes=Text;HDR=NO;"";"; } else // AppBitType.Bit64 { if (m_hasHeaderRow) conn = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + m_path + ";" + @"Extended Properties=""Excel 8.0;IMEX=1;ImportMixedTypes=Text;"";"; else conn = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + m_path + ";" + @"Extended Properties=""Excel 8.0;IMEX=1;ImportMixedTypes=Text;HDR=NO;"";"; } return conn; } // 确保连接已经打开。 private void EnsureOpen() { if ((m_conn != null) && (m_conn.State == ConnectionState.Open)) return; string connStr = GetConnString(); m_conn = new OleDbConnection(connStr); m_conn.Open(); } // private string GetFirstSheetName() { EnsureOpen(); DataTable sheetNames = m_conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" }); return sheetNames.Rows[0].Table.Rows[0]["TABLE_NAME"].ToString().Trim(); } public DataSet OpenDataSet(string sql) { EnsureOpen(); DataSet ds = new DataSet(); OleDbDataAdapter ad = new OleDbDataAdapter(sql, m_conn); ad.Fill(ds, "table1"); return ds; } public DataTable OpenDataTable(string sql) { EnsureOpen(); DataTable dt = new DataTable("table1"); OleDbDataAdapter ad = new OleDbDataAdapter(sql, m_conn); ad.Fill(dt); return dt; } /// /// 读取Excel中指定Sheet的数据到Dataset中。 /// /// Excel文件路径。 /// sheet名称。 /// 读取数据的栏目。 /// 读取数据后是否删除临时excel文件。 /// 错误信息。 /// 如果读取数据正常,返回数据集;否则,返回null,在errorMessage含有异常信息。 public static DataSet ReadExcel(string path, string sheetName, string columns, bool deleteFile, ref string errorMessage) { PlatformID pid = Environment.OSVersion.Platform; if (pid == PlatformID.Unix) bOLEDB = false; if (bOLEDB) return ReadExcel(path, sheetName, columns, true, deleteFile, ref errorMessage); else return ReadExcel_NPOI(path, sheetName, 0, true, ref errorMessage); } /// /// 读取Excel中指定Sheet的数据到Dataset中--。 /// /// Excel文件路径。 /// sheet名称。 /// 读取数据的栏目。 /// Excel第一行是否是标题行。 /// 读取数据后是否删除临时excel文件。 /// 错误信息。 /// 如果读取数据正常,返回数据集;否则,返回null,在errorMessage含有异常信息。 public static DataSet ReadExcel(string path, string sheetName, string columns, bool hasHeaderRow, bool deleteFile, ref string errorMessage) { if (bOLEDB) { string sOldSheet = sheetName; try { using (TExcelData excel = new TExcelData(path, hasHeaderRow, deleteFile)) { // 如果未指定Sheet名,则使用按Sheet名称排序后的第一个Sheet。 if (sheetName.Trim().Equals("")) sheetName = excel.GetFirstSheetName(); else sheetName = sheetName + "$"; string sql; if (string.IsNullOrEmpty(columns)) { sql = "select * from [" + sheetName + "]"; } else { sql = "select " + columns + " from [" + sheetName + "]"; } return excel.OpenDataSet(sql); } } catch (Exception ex) { errorMessage = ex.Message; if (errorMessage.Contains("注册") || (errorMessage.IndexOf("OLEDB", StringComparison.OrdinalIgnoreCase) >= 0) || errorMessage.Contains("OleDb")) bOLEDB = false; else return null; } try { if (!bOLEDB) { errorMessage = ""; return ReadExcel_NPOI(path, sOldSheet, 0, hasHeaderRow, ref errorMessage); } } catch (Exception ex) { errorMessage = ex.Message; if (errorMessage.Contains("注册") || (errorMessage.IndexOf("OLEDB", StringComparison.OrdinalIgnoreCase) >= 0)) bOLEDB = false; return null; } return null; } else { return ReadExcel_NPOI(path, sheetName, 0, hasHeaderRow, ref errorMessage); } } /// /// 根据查询语句读取Excel中的数据到Dataset中。 /// /// Excel文件路径。 /// 查询的sql语句。 /// 读取数据后是否删除临时excel文件。 /// 错误信息。 /// 如果读取数据正常,返回数据集;否则,返回null,在errorMessage含有异常信息。 public static DataSet ReadExcel(string path, string sql, bool deleteFile, ref string errorMessage) { PlatformID pid = Environment.OSVersion.Platform; if (pid == PlatformID.Unix) bOLEDB = false; if (bOLEDB) return ReadExcel(path, sql, true, deleteFile, ref errorMessage); else return ReadExcel_NPOI(path, 0, true, ref errorMessage); } /// /// 根据查询语句读取Excel中的数据到Dataset中。 /// /// Excel文件路径。 /// 查询的sql语句。 /// Excel第一行是否是标题行。 /// 读取数据后是否删除临时excel文件。 /// 错误信息。 /// 如果读取数据正常,返回数据集;否则,返回null,在errorMessage含有异常信息。 public static DataSet ReadExcel(string path, string sql, bool hasHeaderRow, bool deleteFile, ref string errorMessage) { try { using (TExcelData excel = new TExcelData(path, hasHeaderRow, deleteFile)) { if (sql.Trim().Equals("")) { errorMessage = "查询语句为空!"; return null; } return excel.OpenDataSet(sql); } } catch (Exception ex) { errorMessage = ex.Message; return null; } } /// /// 读取Excel文件返回DataSet。 /// /// Excel文件全路径 /// 从哪一行开始读取,一般为0 /// 读取的第一行是否作为DataSet的栏目名,一般为true /// public static DataSet ReadExcel_NPOI(string filePath, int fromRowIndex, bool hasHeaderRow, ref string errorMessage) { return ReadExcel_NPOI(filePath, "", fromRowIndex, hasHeaderRow, ref errorMessage); } /// /// 读取Excel文件返回DataSet。 /// /// Excel文件全路径 /// Sheet名 /// 从哪一行开始读取,一般为0 /// 读取的第一行是否作为DataSet的栏目名,一般为true /// public static DataSet ReadExcel_NPOI(string filePath, string SheetName, int fromRowIndex, bool hasHeaderRow, ref string errorMessage) { string[] sheetNames = new string[1]; sheetNames[0] = SheetName; return ReadExcel_NPOI(filePath, sheetNames, fromRowIndex, hasHeaderRow, ref errorMessage); } /// /// 读取Excel文件返回DataSet。循环sheetName数组里每一个sheetName读取到一个DataTable里。 /// /// Excel文件全路径 /// sheetName数组 /// 从哪一行开始读取,一般为0 /// 读取的第一行是否作为DataSet的栏目名,一般为true /// public static DataSet ReadExcel_NPOI(string filePath, string[] sheetNames, int fromRowIndex, bool hasHeaderRow, ref string errorMessage) { try { DataSet ds = new DataSet(); if (sheetNames == null) return ds; else { HSSFWorkbook wk = null; FileStream fs = File.OpenRead(filePath); wk = new HSSFWorkbook(fs);//把xls文件中的数据写入wk中 //wk = new XSSFWorkbook(fs);//把xlsx文件中的数据写入wk中,暂不支持 fs.Close(); for (int k = 0; k < sheetNames.Length; k++) { string SheetName = sheetNames[k].Trim(); ISheet sheet = SheetName.Equals("") ? wk.GetSheetAt(0) : wk.GetSheet(SheetName); if (sheet == null) continue; SheetName = sheet.SheetName; if (ds.Tables.Contains(SheetName)) continue; else ds.Tables.Add(SheetName); int minCellNum = -1;//最小有效列数 int maxCellNum = -1;//最大有效列数 for (int i = sheet.FirstRowNum; i <= sheet.LastRowNum; i++) { IRow iRow = sheet.GetRow(i); if (iRow != null && iRow.Cells.Count > 0) { if (minCellNum == -1) minCellNum = iRow.FirstCellNum; else { if (iRow.FirstCellNum < minCellNum) minCellNum = iRow.FirstCellNum; } if (maxCellNum == -1) maxCellNum = iRow.LastCellNum; else { if (iRow.LastCellNum > maxCellNum) maxCellNum = iRow.LastCellNum; } } } IRow headerRow = sheet.GetRow(fromRowIndex); //添加列 for (int i = minCellNum; i < maxCellNum; i++) { if (i < headerRow.FirstCellNum || i >= headerRow.LastCellNum) { DataColumn column = new DataColumn("F" + Convert.ToString(i + 1)); ds.Tables[SheetName].Columns.Add(column); } else { if (hasHeaderRow)//第一行为标题行 { DataColumn column = new DataColumn(headerRow.GetCell(i) == null ? " " : headerRow.GetCell(i).StringCellValue); ds.Tables[SheetName].Columns.Add(column); } else { DataColumn column = new DataColumn("F" + Convert.ToString(i + 1)); ds.Tables[SheetName].Columns.Add(column); } } } //添加行 int iFirstLine = fromRowIndex; if (hasHeaderRow) iFirstLine = fromRowIndex + 1; for (int i = iFirstLine; i <= sheet.LastRowNum; i++) { IRow row = sheet.GetRow(i); DataRow dataRow = ds.Tables[SheetName].NewRow(); if (row != null && row.Cells.Count > 0) { for (int j = row.FirstCellNum; j < row.LastCellNum; j++) { if (row.GetCell(j) != null) dataRow[j] = GetCellValue(row.GetCell(j)); } } ds.Tables[SheetName].Rows.Add(dataRow); } } } return ds; } catch (Exception ex) { errorMessage = ex.Message; return null; } } /// /// 读取DataSet生成Excel文件。将数据集填充到指定路径的电子表格中(数据集里多个table对应电子表格的多个sheet页)。 /// /// Excel文件全路径 /// 数据集 /// public static void CreateExcel_NPOI(string filePath, DataSet ds, ref string errorMessage) { CreateExcel_NPOI(filePath, ds, true, null, null, ref errorMessage); } /// /// 读取DataSet生成Excel文件。将数据集填充到指定路径的电子表格中(数据集里多个table对应电子表格的多个sheet页)。 /// /// Excel文件全路径 /// 数据集 /// DataSet的栏目名是否作为Excel的第一行,一般为true /// public static void CreateExcel_NPOI(string filePath, DataSet ds, bool ColNameFirstRow, ref string errorMessage) { CreateExcel_NPOI(filePath, ds, ColNameFirstRow, null, null, ref errorMessage); } /// /// 读取DataSet生成Excel文件。将数据集填充到指定路径的电子表格中(数据集里多个table对应电子表格的多个sheet页)。 /// /// Excel文件全路径 /// 数据集 /// DataSet的栏目名是否作为Excel的第一行,一般为true /// 给指定单元格增加批注 参数一:指定单元格的位置,比如A1、B2、AA1、AAA1参数二:指定单元格上显示的批注内容 /// 设置单元格格式为自定义格式 参数一:指定栏目位置,比如A、B、C 参数二:设置单元格自定义格式,比如"#,##0.00;-#,##0.00;#"代表两位小数 /// public static void CreateExcel_NPOI(string filePath, DataSet ds, bool ColNameFirstRow, NpoiCellData CellData, NpoiSheetData SheetData, ref string errorMessage) { try { if (ds.Tables.Count <= 0) return; if (string.IsNullOrEmpty(filePath)) return; HSSFWorkbook work = new HSSFWorkbook(); for (int i = 0; i < ds.Tables.Count; i++) { ISheet sheet = work.CreateSheet(ds.Tables[i].TableName); if (SheetData != null) sheet.CreateFreezePane(SheetData.FreezePaneCols, SheetData.FreezePaneRows); //设置栏目头和行内容的字体样式 ICellStyle cellHeadStyleDefault = work.CreateCellStyle(); ICellStyle cellStyleDefault = work.CreateCellStyle(); IFont fontHead = work.CreateFont(); fontHead.FontHeightInPoints = 9; fontHead.FontName = "宋体"; cellHeadStyleDefault.SetFont(fontHead); cellHeadStyleDefault.Alignment = HorizontalAlignment.Center; cellHeadStyleDefault.FillForegroundColor = HSSFColor.Grey25Percent.Index; cellHeadStyleDefault.FillPattern = FillPattern.SolidForeground; IFont font = work.CreateFont(); font.FontHeightInPoints = 9; font.FontName = "宋体"; cellStyleDefault.SetFont(font); //用户指定了栏目格式的,按栏目创建好ICellStyle,方便下方循环单元格时直接使用 Dictionary dicColumnStyle = new Dictionary(); Dictionary dicColumnFormula = new Dictionary(); if (SheetData != null) { if (SheetData.ColumnStyle != null) { IDataFormat format = work.CreateDataFormat();//日期、数值类型的指定 foreach (string col in SheetData.ColumnStyle.Keys) { ICellStyle cellStyleEx = work.CreateCellStyle(); string sformula = ""; cellStyleEx.SetFont(font); NpoiColumnStyle tCellStyle = SheetData.ColumnStyle[col]; if (tCellStyle != null && !tCellStyle.DataFormat.Equals("")) { cellStyleEx.DataFormat = format.GetFormat(tCellStyle.DataFormat); sformula = tCellStyle.Formula; } dicColumnStyle.Add(col, cellStyleEx); dicColumnFormula.Add(col, sformula); sheet.SetDefaultColumnStyle(columnNameToIndex(col), cellStyleEx); if (tCellStyle != null && tCellStyle.ColWidth != -1.0) { sheet.SetColumnWidth(columnNameToIndex(col), Pixel2ExcelWidth(tCellStyle.ColWidth)); } } } } if (ColNameFirstRow) { IRow colrow = sheet.CreateRow(0); for (int j = 0; j < ds.Tables[i].Columns.Count; j++) { ICell cell = null; string sColumnName = ds.Tables[i].Columns[j].Caption.Trim(); if (sColumnName.Equals("")) sColumnName = ds.Tables[i].Columns[j].ColumnName.Trim(); if (SheetData != null) { string ColReference = ColIndexToReference(j); NpoiColumnType tCellType = NpoiColumnType.String; cell = colrow.CreateCell(j, CellType.String);//栏目行固定是String类型 cell.CellStyle = cellHeadStyleDefault; switch (tCellType) { case NpoiColumnType.String: cell.SetCellValue(sColumnName); break; case NpoiColumnType.Double: double doubV = 0; double.TryParse(sColumnName, out doubV); cell.SetCellValue(doubV); break; case NpoiColumnType.Boolean: bool boolV = false; bool.TryParse(sColumnName, out boolV); cell.SetCellValue(boolV); break; case NpoiColumnType.DateTime: cell.SetCellValue(sColumnName); break; case NpoiColumnType.Date: cell.SetCellValue(sColumnName); break; default: cell.SetCellValue(sColumnName); break; } } else { cell = colrow.CreateCell(j, CellType.String); cell.CellStyle = cellHeadStyleDefault; cell.SetCellValue(sColumnName); } if (CellData != null) { string CellReference = GetCellReference(cell);//取坐标位置 if ((CellData.CellComment != null) && (CellData.CellComment.ContainsKey(CellReference))) { string sComment = CellData.CellComment[CellReference]; if (!sComment.Equals("")) { IDrawing draw = sheet.CreateDrawingPatriarch(); IComment comment = draw.CreateCellComment(new HSSFClientAnchor(j, 0, j + 1, 0 + 2, j + 1, 0, j + 2, 2)); comment.String = new HSSFRichTextString(sComment); cell.CellComment = comment; } } if ((CellData.CellFormula != null) && (CellData.CellFormula.ContainsKey(CellReference))) { string sFormula = CellData.CellFormula[CellReference]; if (!sFormula.Equals("")) { cell.CellFormula = sFormula; } } if ((CellData.CellColor != null) && (CellData.CellColor.ContainsKey(CellReference))) { short sColorindex = CellData.CellColor[CellReference]; ICellStyle cellStyleColor = work.CreateCellStyle(); cellStyleColor.FillForegroundColor = sColorindex; if ((CellData.CellFillPattern != null) && (CellData.CellFillPattern.ContainsKey(CellReference))) { FillPattern fill = (FillPattern)CellData.CellFillPattern[CellReference]; if (fill != null) { cellStyleColor.FillPattern = fill; } } cell.CellStyle = cellStyleColor; } } } for (int k = 0; k < ds.Tables[i].Rows.Count; k++) { IRow row = sheet.CreateRow(k + 1); for (int j = 0; j < ds.Tables[i].Columns.Count; j++) { ICell cell = null; if (SheetData != null) { string ColReference = ColIndexToReference(j); NpoiColumnType tCellType = NpoiColumnType.String; if (SheetData.ColumnType != null && SheetData.ColumnType.ContainsKey(ColReference)) { tCellType = SheetData.ColumnType[ColReference]; } switch (tCellType) { case NpoiColumnType.String: cell = row.CreateCell(j, CellType.String); break; case NpoiColumnType.Double: cell = row.CreateCell(j, CellType.Numeric); break; case NpoiColumnType.Boolean: cell = row.CreateCell(j, CellType.Boolean); break; case NpoiColumnType.DateTime: cell = row.CreateCell(j, CellType.String); break; case NpoiColumnType.Date: cell = row.CreateCell(j, CellType.String); break; default: row.CreateCell(j, CellType.String); break; } if (dicColumnStyle != null && dicColumnStyle.ContainsKey(ColReference)) cell.CellStyle = dicColumnStyle[ColReference]; else cell.CellStyle = cellStyleDefault; switch (tCellType) { case NpoiColumnType.String: cell.SetCellValue(ds.Tables[i].Rows[k][j].ToString().Trim()); break; case NpoiColumnType.Double: double doubV = 0; double.TryParse(ds.Tables[i].Rows[k][j].ToString().Trim(), out doubV); cell.SetCellValue(doubV); break; case NpoiColumnType.Boolean: bool boolV = false; bool.TryParse(ds.Tables[i].Rows[k][j].ToString().Trim(), out boolV); cell.SetCellValue(boolV); break; case NpoiColumnType.DateTime: cell.SetCellValue(ds.Tables[i].Rows[k][j].ToString().Trim()); break; case NpoiColumnType.Date: cell.SetCellValue(ds.Tables[i].Rows[k][j].ToString().Trim()); break; default: cell.SetCellValue(ds.Tables[i].Rows[k][j].ToString().Trim()); break; } //设置公式 if (dicColumnFormula != null && dicColumnFormula.ContainsKey(ColReference) && !dicColumnFormula[ColReference].Equals("") && cell.CellType == CellType.String) { cell.CellFormula = dicColumnFormula[ColReference]; } } else { cell = row.CreateCell(j, CellType.String); cell.CellStyle = cellStyleDefault; cell.SetCellValue(ds.Tables[i].Rows[k][j].ToString().Trim()); } if (CellData != null) { string CellReference = GetCellReference(cell); if ((CellData.CellComment != null) && (CellData.CellComment.ContainsKey(CellReference))) { string sComment = CellData.CellComment[CellReference]; if (!sComment.Equals("")) { IDrawing draw = sheet.CreateDrawingPatriarch(); IComment comment = draw.CreateCellComment(new HSSFClientAnchor(j, k, j + 1, k + 2, j + 1, k + 1, j + 2, k + 3)); comment.String = new HSSFRichTextString(sComment); cell.CellComment = comment; } } if ((CellData.CellFormula != null) && (CellData.CellFormula.ContainsKey(CellReference))) { string sFormula = CellData.CellFormula[CellReference]; if (!sFormula.Equals("")) { cell.CellFormula = sFormula; } } if ((CellData.CellColor != null) && (CellData.CellColor.ContainsKey(CellReference))) { short sColorindex = CellData.CellColor[CellReference]; ICellStyle cellStyleColor = work.CreateCellStyle(); cellStyleColor.FillForegroundColor = sColorindex; if ((CellData.CellFillPattern != null) && (CellData.CellFillPattern.ContainsKey(CellReference))) { FillPattern fill = (FillPattern)CellData.CellFillPattern[CellReference]; if (fill != null) { cellStyleColor.FillPattern = fill; } } cell.CellStyle = cellStyleColor; } } } } } else { for (int k = 0; k < ds.Tables[i].Rows.Count; k++) { IRow row = sheet.CreateRow(k); for (int j = 0; j < ds.Tables[i].Columns.Count; j++) { ICell cell = null; if (SheetData != null) { string ColReference = ColIndexToReference(j); NpoiColumnType tCellType = NpoiColumnType.String; if (SheetData.ColumnType != null && SheetData.ColumnType.ContainsKey(ColReference)) { tCellType = SheetData.ColumnType[ColReference]; } switch (tCellType) { case NpoiColumnType.String: cell = row.CreateCell(j, CellType.String); break; case NpoiColumnType.Double: cell = row.CreateCell(j, CellType.Numeric); break; case NpoiColumnType.Boolean: cell = row.CreateCell(j, CellType.Boolean); break; case NpoiColumnType.DateTime: cell = row.CreateCell(j, CellType.String); break; case NpoiColumnType.Date: cell = row.CreateCell(j, CellType.String); break; default: row.CreateCell(j, CellType.String); break; } if (dicColumnStyle != null && dicColumnStyle.ContainsKey(ColReference)) cell.CellStyle = dicColumnStyle[ColReference]; else cell.CellStyle = cellStyleDefault; switch (tCellType) { case NpoiColumnType.String: cell.SetCellValue(ds.Tables[i].Rows[k][j].ToString().Trim()); break; case NpoiColumnType.Double: double doubV = 0; double.TryParse(ds.Tables[i].Rows[k][j].ToString().Trim(), out doubV); cell.SetCellValue(doubV); break; case NpoiColumnType.Boolean: bool boolV = false; bool.TryParse(ds.Tables[i].Rows[k][j].ToString().Trim(), out boolV); cell.SetCellValue(boolV); break; case NpoiColumnType.DateTime: cell.SetCellValue(ds.Tables[i].Rows[k][j].ToString().Trim()); break; case NpoiColumnType.Date: cell.SetCellValue(ds.Tables[i].Rows[k][j].ToString().Trim()); break; default: cell.SetCellValue(ds.Tables[i].Rows[k][j].ToString().Trim()); break; } //设置公式 if (dicColumnFormula != null && dicColumnFormula.ContainsKey(ColReference) && !dicColumnFormula[ColReference].Equals("") && cell.CellType == CellType.String) { cell.CellFormula = dicColumnFormula[ColReference]; } } else { cell = row.CreateCell(j, CellType.String); cell.CellStyle = cellStyleDefault; cell.SetCellValue(ds.Tables[i].Rows[k][j].ToString().Trim()); } if (CellData != null) { string CellReference = GetCellReference(cell); if ((CellData.CellComment != null) && (CellData.CellComment.ContainsKey(CellReference))) { string sComment = CellData.CellComment[CellReference]; if (!sComment.Equals("")) { IDrawing draw = sheet.CreateDrawingPatriarch(); IComment comment = draw.CreateCellComment(new HSSFClientAnchor(j, k, j + 1, k + 2, j + 1, k + 1, j + 2, k + 3)); comment.String = new HSSFRichTextString(sComment); cell.CellComment = comment; } } if ((CellData.CellFormula != null) && (CellData.CellFormula.ContainsKey(CellReference))) { string sFormula = CellData.CellFormula[CellReference]; if (!sFormula.Equals("")) { cell.CellFormula = sFormula; } } if ((CellData.CellColor != null) && (CellData.CellColor.ContainsKey(CellReference))) { short sColorindex = CellData.CellColor[CellReference]; ICellStyle cellStyleColor = work.CreateCellStyle(); cellStyleColor.FillForegroundColor = sColorindex; if ((CellData.CellFillPattern != null) && (CellData.CellFillPattern.ContainsKey(CellReference))) { FillPattern fill = (FillPattern)CellData.CellFillPattern[CellReference]; if (fill != null) { cellStyleColor.FillPattern = fill; } } cell.CellStyle = cellStyleColor; } } } } } } using (FileStream fs = File.OpenWrite(filePath)) //打开一个xls文件,如果没有则自行创建,如果存在则在创建是不要打开该文件! { work.Write(fs); //向打开的这个xls文件中写入mySheet表并保存。 fs.Close(); } } catch (Exception ex) { errorMessage = ex.Message.Equals("") ? ex.InnerException.Message : ex.Message; } } /// /// 读取XLSX类型Excel文件返回DataSet。 /// /// Excel文件全路径 /// 从哪一行开始读取,一般为0 /// 读取的第一行是否作为DataSet的栏目名,一般为true /// public static DataSet ReadExcel_XLSX_NPOI(string filePath, int fromRowIndex, bool hasHeaderRow, ref string errorMessage) { return ReadExcel_XLSX_NPOI(filePath, "", fromRowIndex, hasHeaderRow, ref errorMessage); } /// /// 读取XLSX类型Excel文件返回DataSet。 /// /// Excel文件全路径 /// Sheet名 /// 从哪一行开始读取,一般为0 /// 读取的第一行是否作为DataSet的栏目名,一般为true /// public static DataSet ReadExcel_XLSX_NPOI(string filePath, string SheetName, int fromRowIndex, bool hasHeaderRow, ref string errorMessage) { string[] sheetNames = new string[1]; sheetNames[0] = SheetName; return ReadExcel_XLSX_NPOI(filePath, sheetNames, fromRowIndex, hasHeaderRow, ref errorMessage); } /// /// 读取XLSX类型Excel文件返回DataSet。循环sheetName数组里每一个sheetName读取到一个DataTable里。 /// /// Excel文件全路径 /// sheetName数组 /// 从哪一行开始读取,一般为0 /// 读取的第一行是否作为DataSet的栏目名,一般为true /// public static DataSet ReadExcel_XLSX_NPOI(string filePath, string[] sheetNames, int fromRowIndex, bool hasHeaderRow, ref string errorMessage) { try { DataSet ds = new DataSet(); if (sheetNames == null) return ds; else { XSSFWorkbook wk = null; FileStream fs = File.OpenRead(filePath); wk = new XSSFWorkbook(fs);//把xlsx文件中的数据写入wk中 fs.Close(); for (int k = 0; k < sheetNames.Length; k++) { string SheetName = sheetNames[k].Trim(); ISheet sheet = SheetName.Equals("") ? wk.GetSheetAt(0) : wk.GetSheet(SheetName); if (sheet == null) continue; SheetName = sheet.SheetName; if (ds.Tables.Contains(SheetName)) continue; else ds.Tables.Add(SheetName); int minCellNum = -1;//最小有效列数 int maxCellNum = -1;//最大有效列数 for (int i = sheet.FirstRowNum; i <= sheet.LastRowNum; i++) { IRow iRow = sheet.GetRow(i); if (iRow != null && iRow.Cells.Count > 0) { if (minCellNum == -1) minCellNum = iRow.FirstCellNum; else { if (iRow.FirstCellNum < minCellNum) minCellNum = iRow.FirstCellNum; } if (maxCellNum == -1) maxCellNum = iRow.LastCellNum; else { if (iRow.LastCellNum > maxCellNum) maxCellNum = iRow.LastCellNum; } } } IRow headerRow = sheet.GetRow(fromRowIndex); //添加列 for (int i = minCellNum; i < maxCellNum; i++) { if (i < headerRow.FirstCellNum || i >= headerRow.LastCellNum) { DataColumn column = new DataColumn("F" + Convert.ToString(i + 1)); ds.Tables[SheetName].Columns.Add(column); } else { if (hasHeaderRow)//第一行为标题行 { DataColumn column = new DataColumn(headerRow.GetCell(i) == null ? " " : headerRow.GetCell(i).StringCellValue); ds.Tables[SheetName].Columns.Add(column); } else { DataColumn column = new DataColumn("F" + Convert.ToString(i + 1)); ds.Tables[SheetName].Columns.Add(column); } } } //添加行 int iFirstLine = fromRowIndex; if (hasHeaderRow) iFirstLine = fromRowIndex + 1; for (int i = iFirstLine; i <= sheet.LastRowNum; i++) { IRow row = sheet.GetRow(i); DataRow dataRow = ds.Tables[SheetName].NewRow(); if (row != null && row.Cells.Count > 0) { for (int j = row.FirstCellNum; j < row.LastCellNum; j++) { if (row.GetCell(j) != null) dataRow[j] = GetCellValue(row.GetCell(j)); } } ds.Tables[SheetName].Rows.Add(dataRow); } } } return ds; } catch (Exception ex) { errorMessage = ex.Message; return null; } } /// /// 读取DataSet生成XLSX类型Excel文件。将数据集填充到指定路径的电子表格中(数据集里多个table对应电子表格的多个sheet页)。 /// /// Excel文件全路径 /// 数据集 /// public static void CreateExcel_XLSX_NPOI(string filePath, DataSet ds, ref string errorMessage) { CreateExcel_XLSX_NPOI(filePath, ds, true, null, null, ref errorMessage); } /// /// 读取DataSet生成XLSX类型Excel文件。将数据集填充到指定路径的电子表格中(数据集里多个table对应电子表格的多个sheet页)。 /// /// Excel文件全路径 /// 数据集 /// DataSet的栏目名是否作为Excel的第一行,一般为true /// public static void CreateExcel_XLSX_NPOI(string filePath, DataSet ds, bool ColNameFirstRow, ref string errorMessage) { CreateExcel_XLSX_NPOI(filePath, ds, ColNameFirstRow, null, null, ref errorMessage); } /// /// 读取DataSet生成XLSX类型Excel文件。将数据集填充到指定路径的电子表格中(数据集里多个table对应电子表格的多个sheet页)。 /// /// Excel文件全路径 /// 数据集 /// DataSet的栏目名是否作为Excel的第一行,一般为true /// 给指定单元格增加批注 参数一:指定单元格的位置,比如A1、B2、AA1、AAA1参数二:指定单元格上显示的批注内容 /// 设置单元格格式为自定义格式 参数一:指定栏目位置,比如A、B、C 参数二:设置单元格自定义格式,比如"#,##0.00;-#,##0.00;#"代表两位小数 /// public static void CreateExcel_XLSX_NPOI(string filePath, DataSet ds, bool ColNameFirstRow, NpoiCellData CellData, NpoiSheetData SheetData, ref string errorMessage) { try { if (ds.Tables.Count <= 0) return; if (string.IsNullOrEmpty(filePath)) return; XSSFWorkbook work = new XSSFWorkbook(); for (int i = 0; i < ds.Tables.Count; i++) { ISheet sheet = work.CreateSheet(ds.Tables[i].TableName); if (SheetData != null) sheet.CreateFreezePane(SheetData.FreezePaneCols, SheetData.FreezePaneRows); //设置栏目头和行内容的字体样式 ICellStyle cellHeadStyleDefault = work.CreateCellStyle(); ICellStyle cellStyleDefault = work.CreateCellStyle(); IFont fontHead = work.CreateFont(); fontHead.FontHeightInPoints = 9; fontHead.FontName = "宋体"; cellHeadStyleDefault.SetFont(fontHead); cellHeadStyleDefault.Alignment = HorizontalAlignment.Center; cellHeadStyleDefault.FillForegroundColor = HSSFColor.Grey25Percent.Index; cellHeadStyleDefault.FillPattern = FillPattern.SolidForeground; IFont font = work.CreateFont(); font.FontHeightInPoints = 9; font.FontName = "宋体"; cellStyleDefault.SetFont(font); //用户指定了栏目格式的,按栏目创建好ICellStyle,方便下方循环单元格时直接使用 Dictionary dicColumnStyle = new Dictionary(); Dictionary dicColumnFormula = new Dictionary(); if (SheetData != null) { if (SheetData.ColumnStyle != null) { IDataFormat format = work.CreateDataFormat();//日期、数值类型的指定 foreach (string col in SheetData.ColumnStyle.Keys) { ICellStyle cellStyleEx = work.CreateCellStyle(); string sformula = ""; cellStyleEx.SetFont(font); NpoiColumnStyle tCellStyle = SheetData.ColumnStyle[col]; if (tCellStyle != null && !tCellStyle.DataFormat.Equals("")) { cellStyleEx.DataFormat = format.GetFormat(tCellStyle.DataFormat); sformula = tCellStyle.Formula; } dicColumnStyle.Add(col, cellStyleEx); dicColumnFormula.Add(col, sformula); sheet.SetDefaultColumnStyle(columnNameToIndex(col), cellStyleEx); if (tCellStyle != null && tCellStyle.ColWidth != -1.0) { sheet.SetColumnWidth(columnNameToIndex(col), Pixel2ExcelWidth(tCellStyle.ColWidth)); } } } } if (ColNameFirstRow) { IRow colrow = sheet.CreateRow(0); for (int j = 0; j < ds.Tables[i].Columns.Count; j++) { ICell cell = null; string sColumnName = ds.Tables[i].Columns[j].Caption.Trim(); if (sColumnName.Equals("")) sColumnName = ds.Tables[i].Columns[j].ColumnName.Trim(); if (SheetData != null) { string ColReference = ColIndexToReference(j); NpoiColumnType tCellType = NpoiColumnType.String; cell = colrow.CreateCell(j, CellType.String);//栏目行固定是String类型 cell.CellStyle = cellHeadStyleDefault; //if ((SheetData.ColumnStyle != null) && (SheetData.ColumnStyle.ContainsKey(ColReference))) //{ // NpoiColumnStyle tCellStyle = SheetData.ColumnStyle[ColReference]; // if (tCellStyle != null) // { // IDataFormat format = work.CreateDataFormat();//日期、数值类型的指定 // ICellStyle cellStyleNumberEx = cellHeadStyleDefault; // cellStyleNumberEx.DataFormat = format.GetFormat(tCellStyle.DataFormat); // cell.CellStyle = cellStyleNumberEx; // } //} switch (tCellType) { case NpoiColumnType.String: cell.SetCellValue(sColumnName); break; case NpoiColumnType.Double: double doubV = 0; double.TryParse(sColumnName, out doubV); cell.SetCellValue(doubV); break; case NpoiColumnType.Boolean: bool boolV = false; bool.TryParse(sColumnName, out boolV); cell.SetCellValue(boolV); break; case NpoiColumnType.DateTime: cell.SetCellValue(sColumnName); break; case NpoiColumnType.Date: cell.SetCellValue(sColumnName); break; default: cell.SetCellValue(sColumnName); break; } } else { cell = colrow.CreateCell(j, CellType.String); cell.CellStyle = cellHeadStyleDefault; cell.SetCellValue(sColumnName); } if (CellData != null) { string CellReference = GetCellReference(cell); if ((CellData.CellComment != null) && (CellData.CellComment.ContainsKey(CellReference))) { string sComment = CellData.CellComment[CellReference]; if (!sComment.Equals("")) { IDrawing draw = sheet.CreateDrawingPatriarch(); IComment comment = draw.CreateCellComment(new XSSFClientAnchor(j, 0, j + 1, 0 + 2, j + 1, 0, j + 2, 2)); comment.String = new XSSFRichTextString(sComment); cell.CellComment = comment; } } if ((CellData.CellFormula != null) && (CellData.CellFormula.ContainsKey(CellReference))) { string sFormula = CellData.CellFormula[CellReference]; if (!sFormula.Equals("")) { cell.CellFormula = sFormula; } } if ((CellData.CellColor != null) && (CellData.CellColor.ContainsKey(CellReference))) { short sColorindex = CellData.CellColor[CellReference]; ICellStyle cellStyleColor = work.CreateCellStyle(); cellStyleColor.FillForegroundColor = sColorindex; if ((CellData.CellFillPattern != null) && (CellData.CellFillPattern.ContainsKey(CellReference))) { FillPattern fill = (FillPattern)CellData.CellFillPattern[CellReference]; if (fill != null) { cellStyleColor.FillPattern = fill; } } cell.CellStyle=cellStyleColor; } } } for (int k = 0; k < ds.Tables[i].Rows.Count; k++) { IRow row = sheet.CreateRow(k + 1); for (int j = 0; j < ds.Tables[i].Columns.Count; j++) { ICell cell = null; if (SheetData != null) { string ColReference = ColIndexToReference(j); NpoiColumnType tCellType = NpoiColumnType.String; if (SheetData.ColumnType != null && SheetData.ColumnType.ContainsKey(ColReference)) { tCellType = SheetData.ColumnType[ColReference]; } switch (tCellType) { case NpoiColumnType.String: cell = row.CreateCell(j, CellType.String); break; case NpoiColumnType.Double: cell = row.CreateCell(j, CellType.Numeric); break; case NpoiColumnType.Boolean: cell = row.CreateCell(j, CellType.Boolean); break; case NpoiColumnType.DateTime: cell = row.CreateCell(j, CellType.String); break; case NpoiColumnType.Date: cell = row.CreateCell(j, CellType.String); break; default: row.CreateCell(j, CellType.String); break; } if (dicColumnStyle != null && dicColumnStyle.ContainsKey(ColReference)) cell.CellStyle = dicColumnStyle[ColReference]; else cell.CellStyle = cellStyleDefault; switch (tCellType) { case NpoiColumnType.String: cell.SetCellValue(ds.Tables[i].Rows[k][j].ToString().Trim()); break; case NpoiColumnType.Double: double doubV = 0; double.TryParse(ds.Tables[i].Rows[k][j].ToString().Trim(), out doubV); cell.SetCellValue(doubV); break; case NpoiColumnType.Boolean: bool boolV = false; bool.TryParse(ds.Tables[i].Rows[k][j].ToString().Trim(), out boolV); cell.SetCellValue(boolV); break; case NpoiColumnType.DateTime: cell.SetCellValue(ds.Tables[i].Rows[k][j].ToString().Trim()); break; case NpoiColumnType.Date: cell.SetCellValue(ds.Tables[i].Rows[k][j].ToString().Trim()); break; default: cell.SetCellValue(ds.Tables[i].Rows[k][j].ToString().Trim()); break; } //设置公式 if (dicColumnFormula != null && dicColumnFormula.ContainsKey(ColReference) && !dicColumnFormula[ColReference].Equals("") && cell.CellType == CellType.String) { cell.CellFormula = dicColumnFormula[ColReference]; } } else { cell = row.CreateCell(j, CellType.String); cell.CellStyle = cellStyleDefault; cell.SetCellValue(ds.Tables[i].Rows[k][j].ToString().Trim()); } if (CellData != null) { string CellReference = GetCellReference(cell); if ((CellData.CellComment != null) && (CellData.CellComment.ContainsKey(CellReference))) { string sComment = CellData.CellComment[CellReference]; if (!sComment.Equals("")) { IDrawing draw = sheet.CreateDrawingPatriarch(); IComment comment = draw.CreateCellComment(new XSSFClientAnchor(j, k, j + 1, k + 2, j + 1, k + 1, j + 2, k + 3)); comment.String = new XSSFRichTextString(sComment); cell.CellComment = comment; } } if ((CellData.CellFormula != null) && (CellData.CellFormula.ContainsKey(CellReference))) { string sFormula = CellData.CellFormula[CellReference]; if (!sFormula.Equals("")) { cell.CellFormula = sFormula; } } if ((CellData.CellColor != null) && (CellData.CellColor.ContainsKey(CellReference))) { short sColorindex = CellData.CellColor[CellReference]; ICellStyle cellStyleColor = work.CreateCellStyle(); cellStyleColor.FillForegroundColor = sColorindex; if ((CellData.CellFillPattern != null) && (CellData.CellFillPattern.ContainsKey(CellReference))) { FillPattern fill = (FillPattern)CellData.CellFillPattern[CellReference]; if (fill != null) { cellStyleColor.FillPattern = fill; } } cell.CellStyle = cellStyleColor; } } } } } else { for (int k = 0; k < ds.Tables[i].Rows.Count; k++) { IRow row = sheet.CreateRow(k); for (int j = 0; j < ds.Tables[i].Columns.Count; j++) { ICell cell = null; if (SheetData != null) { string ColReference = ColIndexToReference(j); NpoiColumnType tCellType = NpoiColumnType.String; if (SheetData.ColumnType != null && SheetData.ColumnType.ContainsKey(ColReference)) { tCellType = SheetData.ColumnType[ColReference]; } switch (tCellType) { case NpoiColumnType.String: cell = row.CreateCell(j, CellType.String); break; case NpoiColumnType.Double: cell = row.CreateCell(j, CellType.Numeric); break; case NpoiColumnType.Boolean: cell = row.CreateCell(j, CellType.Boolean); break; case NpoiColumnType.DateTime: cell = row.CreateCell(j, CellType.String); break; case NpoiColumnType.Date: cell = row.CreateCell(j, CellType.String); break; default: row.CreateCell(j, CellType.String); break; } if (dicColumnStyle != null && dicColumnStyle.ContainsKey(ColReference)) cell.CellStyle = dicColumnStyle[ColReference]; else cell.CellStyle = cellStyleDefault; switch (tCellType) { case NpoiColumnType.String: cell.SetCellValue(ds.Tables[i].Rows[k][j].ToString().Trim()); break; case NpoiColumnType.Double: double doubV = 0; double.TryParse(ds.Tables[i].Rows[k][j].ToString().Trim(), out doubV); cell.SetCellValue(doubV); break; case NpoiColumnType.Boolean: bool boolV = false; bool.TryParse(ds.Tables[i].Rows[k][j].ToString().Trim(), out boolV); cell.SetCellValue(boolV); break; case NpoiColumnType.DateTime: cell.SetCellValue(ds.Tables[i].Rows[k][j].ToString().Trim()); break; case NpoiColumnType.Date: cell.SetCellValue(ds.Tables[i].Rows[k][j].ToString().Trim()); break; default: cell.SetCellValue(ds.Tables[i].Rows[k][j].ToString().Trim()); break; } //设置公式 if (dicColumnFormula != null && dicColumnFormula.ContainsKey(ColReference) && !dicColumnFormula[ColReference].Equals("") && cell.CellType == CellType.String) { cell.CellFormula = dicColumnFormula[ColReference]; } } else { cell = row.CreateCell(j, CellType.String); cell.CellStyle = cellStyleDefault; cell.SetCellValue(ds.Tables[i].Rows[k][j].ToString().Trim()); } if (CellData != null) { string CellReference = GetCellReference(cell); if ((CellData.CellComment != null) && (CellData.CellComment.ContainsKey(CellReference))) { string sComment = CellData.CellComment[CellReference]; if (!sComment.Equals("")) { IDrawing draw = sheet.CreateDrawingPatriarch(); IComment comment = draw.CreateCellComment(new XSSFClientAnchor(j, k, j + 1, k + 2, j + 1, k + 1, j + 2, k + 3)); comment.String = new XSSFRichTextString(sComment); cell.CellComment = comment; } } if ((CellData.CellFormula != null) && (CellData.CellFormula.ContainsKey(CellReference))) { string sFormula = CellData.CellFormula[CellReference]; if (!sFormula.Equals("")) { cell.CellFormula = sFormula; } } if ((CellData.CellColor != null) && (CellData.CellColor.ContainsKey(CellReference))) { short sColorindex = CellData.CellColor[CellReference]; ICellStyle cellStyleColor = work.CreateCellStyle(); cellStyleColor.FillForegroundColor = sColorindex; if ((CellData.CellFillPattern != null) && (CellData.CellFillPattern.ContainsKey(CellReference))) { FillPattern fill = (FillPattern)CellData.CellFillPattern[CellReference]; if (fill != null) { cellStyleColor.FillPattern = fill; } } cell.CellStyle = cellStyleColor; } } } } } } using (FileStream fs = File.OpenWrite(filePath)) //打开一个xlsx文件,如果没有则自行创建,如果存在则在创建是不要打开该文件! { work.Write(fs); //向打开的这个xlsx文件中写入mySheet表并保存。 fs.Close(); } } catch (Exception ex) { errorMessage = ex.Message.Equals("") ? ex.InnerException.Message : ex.Message; } } /// /// 将业务数据写入xls文件中,返回临时文件全路径 /// /// xls文件流 /// 读取指定的Sheet页 /// 首行是否为栏目行 /// 业务数据集 /// 用于匹配行记录的栏目对应关系,格式:xls列坐标,业务数据集栏目 比如:A,BM_BMID /// 根据匹配到的行记录更新哪些栏目,用于存储栏目对应关系,格式:xls列坐标,业务数据集栏目 比如:B,BM_FZR /// 按dicUpdateCol进行更新数据时,指定栏目的数据类型 /// 是否清空未匹配到的行记录的待更新栏目数据 /// 错误信息 /// 返回临时文件全路径 public static string UpdateExcel_NPOI(Stream fileStream, string sSheetName, bool hasHeaderRow, DataSet dsUpd, Dictionary dicMatchedCol, Dictionary dicUpdateCol, NpoiSheetData SheetData, bool bClearNotMatched, ref string errorMessage) { if (sSheetName.Trim().Equals("")) { errorMessage = "未指定Sheet页"; return ""; } if (dsUpd.Tables.Count == 0) { errorMessage = "传入的数据集为空"; return ""; } //FileStream fs1 = File.OpenRead(filePath); try { HSSFWorkbook wk = new HSSFWorkbook(fileStream); ISheet sheet = wk.GetSheet(sSheetName); if (sheet == null) { errorMessage = "未在电子表格中找到工作表:" + sSheetName; return ""; } string strSort = ""; int iSortCount = 0; foreach (string sReference in dicMatchedCol.Keys) { if (!dicMatchedCol[sReference].Trim().Equals("") && dsUpd.Tables[0].Columns.Contains(dicMatchedCol[sReference].Trim()) && !Convert.ToString("," + strSort).Contains("," + dicMatchedCol[sReference].Trim() + ",")) { strSort += dicMatchedCol[sReference].Trim() + ","; iSortCount++; } } strSort = strSort.TrimEnd(','); if (iSortCount != dicMatchedCol.Keys.Count) { errorMessage = "Excel栏目与数据集字段必须一对一匹配"; return ""; } //单元格字体格式 ICellStyle cellStyleDefault = wk.CreateCellStyle(); IFont font = wk.CreateFont(); font.FontHeightInPoints = 9; font.FontName = "宋体"; cellStyleDefault.SetFont(font); DataView dvUpd = new DataView(dsUpd.Tables[0], "", strSort, DataViewRowState.CurrentRows); int ifirstRow = sheet.FirstRowNum; if (hasHeaderRow)//第一行是栏目行 ifirstRow = ifirstRow + 1; for (int i = ifirstRow; i <= sheet.LastRowNum; i++) { object[] obj = new object[dicMatchedCol.Keys.Count]; int k = 0; foreach (string sReference in dicMatchedCol.Keys) { ICell cell = sheet.GetRow(i).GetCell(columnNameToIndex(sReference)); obj[k] = GetCellValue(cell); k++; } DataRowView[] rows = dvUpd.FindRows(obj); if (rows.Length > 0) { foreach (DataRowView row in rows) { foreach (string sReference in dicUpdateCol.Keys)//缺dicUpdateCol的合法性校验 { NpoiColumnType tCellType = NpoiColumnType.String; if (SheetData != null) { if (SheetData.ColumnType != null && SheetData.ColumnType.ContainsKey(sReference)) { tCellType = SheetData.ColumnType[sReference]; } } int colIndex = columnNameToIndex(sReference); ICell cell = sheet.GetRow(i).GetCell(colIndex); if (cell == null)//没有动过的单元格取出来的cell是null { switch (tCellType) { case NpoiColumnType.String: cell = sheet.GetRow(i).CreateCell(colIndex, CellType.String); break; case NpoiColumnType.Double: cell = sheet.GetRow(i).CreateCell(colIndex, CellType.Numeric); break; case NpoiColumnType.Boolean: cell = sheet.GetRow(i).CreateCell(colIndex, CellType.Boolean); break; case NpoiColumnType.DateTime: cell = sheet.GetRow(i).CreateCell(colIndex, CellType.String); break; case NpoiColumnType.Date: cell = sheet.GetRow(i).CreateCell(colIndex, CellType.String); break; default: cell = sheet.GetRow(i).CreateCell(colIndex, CellType.String); break; } cell.CellStyle = cellStyleDefault; } switch (tCellType) { case NpoiColumnType.String: cell.SetCellValue(row[dicUpdateCol[sReference]].ToString().Trim()); break; case NpoiColumnType.Double: double doubV = 0; double.TryParse(row[dicUpdateCol[sReference]].ToString().Trim(), out doubV); cell.SetCellValue(doubV); break; case NpoiColumnType.Boolean: bool boolV = false; bool.TryParse(row[dicUpdateCol[sReference]].ToString().Trim(), out boolV); cell.SetCellValue(boolV); break; case NpoiColumnType.DateTime: cell.SetCellValue(row[dicUpdateCol[sReference]].ToString().Trim()); break; case NpoiColumnType.Date: cell.SetCellValue(row[dicUpdateCol[sReference]].ToString().Trim()); break; default: cell.SetCellValue(row[dicUpdateCol[sReference]].ToString().Trim()); break; } } } } else { if (bClearNotMatched) { foreach (string sReference in dicUpdateCol.Keys)//缺dicUpdateCol的合法性校验 { NpoiColumnType tCellType = NpoiColumnType.String; if (SheetData != null) { if (SheetData.ColumnType != null && SheetData.ColumnType.ContainsKey(sReference)) { tCellType = SheetData.ColumnType[sReference]; } } int colIndex = columnNameToIndex(sReference); ICell cell = sheet.GetRow(i).GetCell(colIndex); if (cell == null)//没有动过的单元格取出来的cell是null { switch (tCellType) { case NpoiColumnType.String: cell = sheet.GetRow(i).CreateCell(colIndex, CellType.String); break; case NpoiColumnType.Double: cell = sheet.GetRow(i).CreateCell(colIndex, CellType.Numeric); break; case NpoiColumnType.Boolean: cell = sheet.GetRow(i).CreateCell(colIndex, CellType.Boolean); break; case NpoiColumnType.DateTime: cell = sheet.GetRow(i).CreateCell(colIndex, CellType.String); break; case NpoiColumnType.Date: cell = sheet.GetRow(i).CreateCell(colIndex, CellType.String); break; default: cell = sheet.GetRow(i).CreateCell(colIndex, CellType.String); break; } cell.CellStyle = cellStyleDefault; } switch (tCellType) { case NpoiColumnType.String: cell.SetCellValue(""); break; case NpoiColumnType.Double: cell.SetCellValue(0); break; case NpoiColumnType.Boolean: cell.SetCellValue(false); break; case NpoiColumnType.DateTime: cell.SetCellValue(""); break; case NpoiColumnType.Date: cell.SetCellValue(""); break; default: cell.SetCellValue(""); break; } } } } } string m_tmpFilePath = WorkDirectory.CombineTempPath(Guid.NewGuid().ToString() + ".xls"); using (FileStream fs = File.OpenWrite(m_tmpFilePath)) //打开一个xls文件,如果没有则自行创建,如果存在则在创建是不要打开该文件! { wk.ForceFormulaRecalculation = true; wk.Write(fs); //向打开的这个xls文件中写入mySheet表并保存。 fs.Close(); return m_tmpFilePath; } } catch (Exception ex) { errorMessage = ex.Message; return ""; } //finally //{ // fs1.Close(); //} } //获取cell的数据,并设置为对应的数据类型 public static object GetCellValue(ICell cell) { object value = null; try { if (cell.CellType != CellType.Blank) { switch (cell.CellType) { case CellType.Numeric: // Date comes here if (DateUtil.IsCellDateFormatted(cell)) { value = cell.DateCellValue; } else { // Numeric type value = cell.NumericCellValue; } break; case CellType.Boolean: // Boolean type value = cell.BooleanCellValue; break; case CellType.Formula: value = cell.NumericCellValue; //公式返回Numeric break; default: // String type value = cell.StringCellValue; break; } } } catch (Exception) { value = ""; } return value; } //获取cell的坐标 public static string GetCellReference(ICell cell) { string cellReference = string.Empty; if (cell != null) cellReference = new CellReference(cell).FormatAsString(); return cellReference; } // DataSet的列序号转列坐标 public static string ColIndexToReference(int index) { string str = ""; bool bflag = false; while (index > 25) { int j = index % 26; str += Convert.ToChar(j + 'A'); index = index / 26; bflag = true; } if (bflag) str += Convert.ToChar(index - 1 + 'A'); else str += Convert.ToChar(index + 'A'); Char[] c = str.ToCharArray(); Array.Reverse(c); return new string(c); } //由Excel中的列坐标转为列序号 public static int columnNameToIndex(string columnName) { if (!Regex.IsMatch(columnName.ToUpper(), @"[A-Z]+")) { throw new Exception("invalid parameter"); } int index = 0; char[] chars = columnName.ToUpper().ToCharArray(); for (int i = 0; i < chars.Length; i++) { index += ((int)chars[i] - (int)'A' + 1) * (int)Math.Pow(26, chars.Length - i - 1); } return index - 1; } private static int Pixel2ExcelWidth(double pixelWidth) { return (int)(pixelWidth * 2 * 256 / 15); } } }