123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744 |
- using NPOI.HSSF.UserModel;
- using NPOI.SS.UserModel;
- using NPOI.XSSF.UserModel;
- using System;
- using System.Collections.Generic;
- using System.Data;
- using System.IO;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows.Forms;
- namespace NX_ExcelClassLibrary
- {
- /// <summary>
- /// 先导智能从Excel操作帮助类
- /// Copyright20181102 (C) sunyalong
- /// 允许修改、添加满足自己项目的需要。
- /// 添加、修改后请详细注释。违者会强制删除不予采用。
- /// </summary>
- public static class LeadExcelHelper
- {
- #region Excel帮助类 私有 操作方法
- /// <summary>
- /// 获取要保存的文件名称(含完整路径)
- /// </summary>
- /// <returns></returns>
- private static string GetSaveFilePath()
- {
- SaveFileDialog saveFileDig = new SaveFileDialog
- {
- Filter = "Excel Office97-2003(*.xls)|*.xls|Excel Office2007及以上(*.xlsx)|*.xlsx",
- FilterIndex = 0,
- Title = "导出到",
- OverwritePrompt = true
- };
- //saveFileDig.InitialDirectory = Common.DesktopDirectory;//设置对话框初始目录
- string filePath = null;
- if (saveFileDig.ShowDialog() == DialogResult.OK)
- {
- filePath = saveFileDig.FileName;
- }
- return filePath;
- }
- /// <summary>
- /// 获取要打开要导入的文件名称(含完整路径)
- /// </summary>
- /// <returns></returns>
- private static string GetOpenFilePath()
- {
- OpenFileDialog openFileDig = new OpenFileDialog
- {
- Filter = "Excel Office97-2003(*.xls)|*.xls|Excel Office2007及以上(*.xlsx)|*.xlsx",
- FilterIndex = 0,
- Title = "打开",
- CheckFileExists = true,
- CheckPathExists = true
- };
- //openFileDig.InitialDirectory = Common.DesktopDirectory;//设置对话框初始目录
- string filePath = null;
- if (openFileDig.ShowDialog() == DialogResult.OK)
- {
- filePath = openFileDig.FileName;
- }
- return filePath;
- }
- /// <summary>
- /// 判断是否为兼容模式(Excel版本.xls或.xlsx)
- /// </summary>
- /// <param name="filePath">Excel路径文件名称字符串路径</param>
- /// <returns></returns>
- private static bool GetIsCompatible(string filePath)
- {
- return filePath.EndsWith(".xls", StringComparison.OrdinalIgnoreCase);
- }
- /// <summary>
- /// 创建工作薄
- /// </summary>
- /// <param name="isCompatible"> true:Excel Office97-2003; false:Excel Office2007及以上 </param>
- /// <returns></returns>
- private static IWorkbook CreateWorkbook(bool isCompatible)
- {
- if (isCompatible)
- {
- return new HSSFWorkbook();
- }
- else
- {
- return new XSSFWorkbook();
- }
- }
- /// <summary>
- /// 创建工作薄(依据文件流)
- /// </summary>
- /// <param name="isCompatible"> true:Excel Office97-2003; false:Excel Office2007及以上 </param>
- /// <param name="stream">文件流</param>
- /// <returns></returns>
- private static IWorkbook CreateWorkbook(bool isCompatible, dynamic stream)
- {
- if (isCompatible)
- {
- return new HSSFWorkbook(stream);
- }
- else
- {
- return new XSSFWorkbook(stream);
- }
- }
- /// <summary>
- /// 创建表格头单元格
- /// </summary>
- /// <param name="workbook">IWorkbook工作薄</param>
- /// <returns></returns>
- private static ICellStyle GetCellStyle(IWorkbook workbook)
- {
- ICellStyle style = workbook.CreateCellStyle();
- style.FillPattern = FillPattern.SolidForeground;
- style.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Grey25Percent.Index;
- return style;
- }
- /// <summary>
- /// 从工作表中生成DataTable
- /// </summary>
- /// <param name="sheet">工作表</param>
- /// <param name="headerRowIndex">行索引</param>
- /// <returns></returns>
- private static DataTable GetDataTableFromSheet(ISheet sheet, int headerRowIndex)
- {
- DataTable table = new DataTable();
- IRow headerRow = sheet.GetRow(headerRowIndex);
- int cellCount = headerRow.LastCellNum;
- for (int i = headerRow.FirstCellNum; i < cellCount; i++)
- {
- if (headerRow.GetCell(i) == null || headerRow.GetCell(i).StringCellValue.Trim() == "")
- {
- // 如果遇到第一个空列,则不再继续向后读取
- cellCount = i;
- break;
- }
- DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);
- table.Columns.Add(column);
- }
- for (int i = (headerRowIndex + 1); i <= sheet.LastRowNum; i++)
- {
- IRow row = sheet.GetRow(i);
- //如果遇到某行的第一个单元格的值为空,则不再继续向下读取
- if (row != null && !string.IsNullOrEmpty(row.GetCell(0).ToString()))
- {
- DataRow dataRow = table.NewRow();
- for (int j = row.FirstCellNum; j < cellCount; j++)
- {
- dataRow[j] = row.GetCell(j).ToString();
- }
- table.Rows.Add(dataRow);
- }
- }
- return table;
- }
- #region 20191116 孙亚龙针对电池测试数据表格开发的方法
- private static DataTable GetDataTableFromSheet(ISheet sheet, int headerRowIndex, ref string ipStr, ref string timeStr)
- {
- DataTable table = new DataTable();
- IRow headerRow = sheet.GetRow(headerRowIndex);
- int cellCount = headerRow.LastCellNum;
- #region 获取行索引为1、2的值
- IRow indexRow1 = sheet.GetRow(1);
- IRow indexRow2 = sheet.GetRow(2);
- ipStr = indexRow1.GetCell(0).StringCellValue.Split(':')[1];
- timeStr = indexRow2.GetCell(0).StringCellValue.Split(':')[1];
- #endregion
- for (int i = headerRow.FirstCellNum; i < cellCount; i++)
- {
- if (headerRow.GetCell(i) == null || headerRow.GetCell(i).StringCellValue.Trim() == "")
- {
- // 如果遇到第一个空列,则不再继续向后读取
- cellCount = i;
- break;
- }
- DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);
- table.Columns.Add(column);
- }
- for (int i = (headerRowIndex + 1); i <= sheet.LastRowNum; i++)
- {
- IRow row = sheet.GetRow(i);
- //如果遇到某行的第一个单元格的值为空,则不再继续向下读取
- if (row != null && !string.IsNullOrEmpty(row.GetCell(0).ToString()))
- {
- DataRow dataRow = table.NewRow();
- for (int j = row.FirstCellNum; j < cellCount; j++)
- {
- dataRow[j] = row.GetCell(j).ToString();
- }
- table.Rows.Add(dataRow);
- }
- }
- return table;
- }
- public static DataSet ImportFromExcel(string excelFilePath, int headerRowIndex, ref string ipStr, ref string timeStr)
- {
- if (string.IsNullOrEmpty(excelFilePath))
- {
- excelFilePath = GetOpenFilePath();
- }
- if (string.IsNullOrEmpty(excelFilePath))
- {
- return null;
- }
- using (FileStream stream = System.IO.File.OpenRead(excelFilePath))
- {
- bool isCompatible = GetIsCompatible(excelFilePath);
- return ImportFromExcel(stream, headerRowIndex, isCompatible, ref ipStr, ref timeStr);
- }
- }
- public static DataSet ImportFromExcel(Stream excelFileStream, int headerRowIndex, bool isCompatible, ref string ipStr, ref string timeStr)
- {
- DataSet ds = new DataSet();
- IWorkbook workbook = CreateWorkbook(isCompatible, excelFileStream);
- for (int i = 0; i < workbook.NumberOfSheets; i++)
- {
- ISheet sheet = workbook.GetSheetAt(i);
- DataTable table = GetDataTableFromSheet(sheet, headerRowIndex, ref ipStr, ref timeStr);
- ds.Tables.Add(table);
- }
- excelFileStream.Close();
- //workbook = null;
- return ds;
- }
- #endregion
- #endregion
- #region Excel帮助类 公共 导出方法
- /// <summary>
- /// 由DataSet导出为Excel
- /// </summary>
- /// <param name="sourceDs">要导出的DataSet</param>
- /// <param name="filePath">Excel文件存放路径</param>
- /// <returns>Excel文件存放路径</returns>
- public static string ExportToExcel(DataSet sourceDs, string filePath = null)
- {
- if (string.IsNullOrEmpty(filePath))
- {
- filePath = GetSaveFilePath();
- }
- if (string.IsNullOrEmpty(filePath))
- {
- return null;
- }
- bool isCompatible = GetIsCompatible(filePath);
- IWorkbook workbook = CreateWorkbook(isCompatible);
- ICellStyle cellStyle = GetCellStyle(workbook);
- for (int i = 0; i < sourceDs.Tables.Count; i++)
- {
- DataTable table = sourceDs.Tables[i];
- string sheetName = "result" + i.ToString();
- ISheet sheet = workbook.CreateSheet(sheetName);
- IRow headerRow = sheet.CreateRow(0);
- // handling header.
- foreach (DataColumn column in table.Columns)
- {
- ICell cell = headerRow.CreateCell(column.Ordinal);
- cell.SetCellValue(column.ColumnName);
- cell.CellStyle = cellStyle;
- }
- // handling value.
- int rowIndex = 1;
- foreach (DataRow row in table.Rows)
- {
- IRow dataRow = sheet.CreateRow(rowIndex);
- foreach (DataColumn column in table.Columns)
- {
- dataRow.CreateCell(column.Ordinal).SetCellValue((row[column] ?? "").ToString());
- }
- rowIndex++;
- }
- }
- FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
- workbook.Write(fs);
- fs.Dispose();
- //workbook = null;
- return filePath;
- }
- /// <summary>
- /// 由DataTable导出Excel
- /// </summary>
- /// <param name="sourceTable">要导出数据的DataTable</param>
- /// <param name="sheetName">工作表名称</param>
- /// <param name="filePath">Excel文件存放路径</param>
- /// <returns>Excel文件存放路径</returns>
- public static string ExportToExcel(DataTable sourceTable, string sheetName = "result", string filePath = null)
- {
- if (sourceTable.Rows.Count <= 0) return null;
- if (string.IsNullOrEmpty(filePath))
- {
- filePath = GetSaveFilePath();
- }
- if (string.IsNullOrEmpty(filePath)) return null;
- bool isCompatible = GetIsCompatible(filePath);
- IWorkbook workbook = CreateWorkbook(isCompatible);
- ICellStyle cellStyle = GetCellStyle(workbook);
- ISheet sheet = workbook.CreateSheet(sheetName);
- IRow headerRow = sheet.CreateRow(0);
- // handling header.
- foreach (DataColumn column in sourceTable.Columns)
- {
- ICell headerCell = headerRow.CreateCell(column.Ordinal);
- headerCell.SetCellValue(column.ColumnName);
- headerCell.CellStyle = cellStyle;
- }
- // handling value.
- int rowIndex = 1;
- foreach (DataRow row in sourceTable.Rows)
- {
- IRow dataRow = sheet.CreateRow(rowIndex);
- foreach (DataColumn column in sourceTable.Columns)
- {
- dataRow.CreateCell(column.Ordinal).SetCellValue((row[column] ?? "").ToString());
- }
- rowIndex++;
- }
- FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
- workbook.Write(fs);
- fs.Dispose();
- //sheet = null;
- //headerRow = null;
- //workbook = null;
- return filePath;
- }
- /// <summary>
- /// 实体类List集合导出为Excel
- /// </summary>
- /// <typeparam name="T">实体类类型</typeparam>
- /// <param name="data">实体类List集合数据</param>
- /// <param name="headerNameList">实体类属性的键值对集合</param>
- /// <param name="sheetName">工作表名称</param>
- /// <param name="filePath">Excel文件存放路径</param>
- /// <returns>Excel文件存放路径</returns>
- public static string ExportToExcel<T>(List<T> data, IList<KeyValuePair<string, string>> headerNameList, string sheetName = "result", string filePath = null) where T : class
- {
- if (data.Count <= 0) return null;
- if (string.IsNullOrEmpty(filePath))
- {
- filePath = GetSaveFilePath();
- }
- if (string.IsNullOrEmpty(filePath)) return null;
- bool isCompatible = GetIsCompatible(filePath);
- IWorkbook workbook = CreateWorkbook(isCompatible);
- ICellStyle cellStyle = GetCellStyle(workbook);
- ISheet sheet = workbook.CreateSheet(sheetName);
- IRow headerRow = sheet.CreateRow(0);
- for (int i = 0; i < headerNameList.Count; i++)
- {
- ICell cell = headerRow.CreateCell(i);
- cell.SetCellValue(headerNameList[i].Value);
- cell.CellStyle = cellStyle;
- }
- Type t = typeof(T);
- int rowIndex = 1;
- foreach (T item in data)
- {
- IRow dataRow = sheet.CreateRow(rowIndex);
- for (int n = 0; n < headerNameList.Count; n++)
- {
- object pValue = t.GetProperty(headerNameList[n].Key).GetValue(item, null);
- dataRow.CreateCell(n).SetCellValue((pValue ?? "").ToString());
- }
- rowIndex++;
- }
- FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
- workbook.Write(fs);
- fs.Dispose();
- //sheet = null;
- //headerRow = null;
- //workbook = null;
- return filePath;
- }
- /// <summary>
- /// 由DataGridView导出为Excel
- /// </summary>
- /// <param name="grid">DataGridView对象</param>
- /// <param name="sheetName">工作表名称</param>
- /// <param name="filePath">Excel文件存放路径</param>
- /// <returns>Excel文件存放路径</returns>
- public static string ExportToExcel(DataGridView grid, string sheetName = "result", string filePath = null)
- {
- if (grid.Rows.Count <= 0) return null;
- if (string.IsNullOrEmpty(filePath))
- {
- filePath = GetSaveFilePath();
- }
- if (string.IsNullOrEmpty(filePath)) return null;
- bool isCompatible = GetIsCompatible(filePath);
- IWorkbook workbook = CreateWorkbook(isCompatible);
- ICellStyle cellStyle = GetCellStyle(workbook);
- ISheet sheet = workbook.CreateSheet(sheetName);
- IRow headerRow = sheet.CreateRow(0);
- for (int i = 0; i < grid.Columns.Count; i++)
- {
- ICell cell = headerRow.CreateCell(i);
- cell.SetCellValue(grid.Columns[i].HeaderText);
- cell.CellStyle = cellStyle;
- }
- int rowIndex = 1;
- foreach (DataGridViewRow row in grid.Rows)
- {
- IRow dataRow = sheet.CreateRow(rowIndex);
- for (int n = 0; n < grid.Columns.Count; n++)
- {
- dataRow.CreateCell(n).SetCellValue((row.Cells[n].Value ?? "").ToString());
- }
- rowIndex++;
- }
- FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
- workbook.Write(fs);
- fs.Dispose();
- //sheet = null;
- //headerRow = null;
- //workbook = null;
- return filePath;
- }
- #endregion
- #region Excel帮助类 公共 导入方法
- /// <summary>
- /// 由Excel文件流导入DataTable
- /// </summary>
- /// <param name="excelFileStream">Excel文件流</param>
- /// <param name="sheetName">Excel工作表名称</param>
- /// <param name="headerRowIndex">Excel表头行索引</param>
- /// <param name="isCompatible">是否为兼容模式</param>
- /// <returns>DataTable</returns>
- public static DataTable ImportFromExcel(Stream excelFileStream, string sheetName, int headerRowIndex, bool isCompatible)
- {
- IWorkbook workbook = CreateWorkbook(isCompatible, excelFileStream);
- ISheet sheet;
- if (int.TryParse(sheetName, out int sheetIndex))
- {
- sheet = workbook.GetSheetAt(sheetIndex);
- }
- else
- {
- sheet = workbook.GetSheet(sheetName);
- }
- DataTable table = GetDataTableFromSheet(sheet, headerRowIndex);
- excelFileStream.Close();
- //workbook = null;
- //sheet = null;
- return table;
- }
- /// <summary>
- /// 由Excel导入DataTable
- /// </summary>
- /// <param name="excelFilePath">Excel文件路径,为物理路径。</param>
- /// <param name="sheetName">Excel工作表名称</param>
- /// <param name="headerRowIndex">Excel表头行索引</param>
- /// <returns>DataTable</returns>
- public static DataTable ImportFromExcel(string excelFilePath, string sheetName, int headerRowIndex)
- {
- if (string.IsNullOrEmpty(excelFilePath))
- {
- excelFilePath = GetOpenFilePath();
- }
- if (string.IsNullOrEmpty(excelFilePath))
- {
- return null;
- }
- using (FileStream stream = System.IO.File.OpenRead(excelFilePath))
- {
- bool isCompatible = GetIsCompatible(excelFilePath);
- return ImportFromExcel(stream, sheetName, headerRowIndex, isCompatible);
- }
- }
- /// <summary>
- /// 由Excel文件流导入DataSet,如果有多个工作表,则导入多个DataTable
- /// </summary>
- /// <param name="excelFileStream">Excel文件流</param>
- /// <param name="headerRowIndex">Excel表头行索引</param>
- /// <param name="isCompatible">是否为兼容模式</param>
- /// <returns>DataSet</returns>
- public static DataSet ImportFromExcel(Stream excelFileStream, int headerRowIndex, bool isCompatible)
- {
- DataSet ds = new DataSet();
- IWorkbook workbook = CreateWorkbook(isCompatible, excelFileStream);
- for (int i = 0; i < workbook.NumberOfSheets; i++)
- {
- ISheet sheet = workbook.GetSheetAt(i);
- DataTable table = GetDataTableFromSheet(sheet, headerRowIndex);
- ds.Tables.Add(table);
- }
- excelFileStream.Close();
- //workbook = null;
- return ds;
- }
- /// <summary>
- /// 由Excel文件导入DataSet,如果有多个工作表,则导入多个DataTable
- /// </summary>
- /// <param name="excelFilePath">Excel文件路径,为物理路径。</param>
- /// <param name="headerRowIndex">Excel表头行索引</param>
- /// <returns>DataSet</returns>
- public static DataSet ImportFromExcel(string excelFilePath, int headerRowIndex)
- {
- if (string.IsNullOrEmpty(excelFilePath))
- {
- excelFilePath = GetOpenFilePath();
- }
- if (string.IsNullOrEmpty(excelFilePath))
- {
- return null;
- }
- using (FileStream stream = System.IO.File.OpenRead(excelFilePath))
- {
- bool isCompatible = GetIsCompatible(excelFilePath);
- return ImportFromExcel(stream, headerRowIndex, isCompatible);
- }
- }
- #endregion
- #region Excel帮助类 公共 转换方法
- /// <summary>
- /// 将Excel的列索引转换为列名,列索引从0开始,列名从A开始。如第0列为A,第1列为B...
- /// </summary>
- /// <param name="index">列索引</param>
- /// <returns>列名,如第0列为A,第1列为B...</returns>
- public static string ConvertColumnIndexToColumnName(int index)
- {
- index += 1;
- int system = 26;
- char[] digArray = new char[100];
- int i = 0;
- while (index > 0)
- {
- int mod = index % system;
- if (mod == 0) mod = system;
- digArray[i++] = (char)(mod - 1 + 'A');
- index = (index - 1) / 26;
- }
- StringBuilder sb = new StringBuilder(i);
- for (int j = i - 1; j >= 0; j--)
- {
- sb.Append(digArray[j]);
- }
- return sb.ToString();
- }
- /// <summary>
- /// 转化日期
- /// </summary>
- /// <param name="date">日期</param>
- /// <returns></returns>
- public static DateTime ConvertToDate(object date)
- {
- string dtStr = (date ?? "").ToString();
- if (DateTime.TryParse(dtStr, out DateTime dt))
- {
- return dt;
- }
- try
- {
- string spStr = "";
- if (dtStr.Contains("-"))
- {
- spStr = "-";
- }
- else if (dtStr.Contains("/"))
- {
- spStr = "/";
- }
- string[] time = dtStr.Split(spStr.ToCharArray());
- int year = Convert.ToInt32(time[2]);
- int month = Convert.ToInt32(time[0]);
- int day = Convert.ToInt32(time[1]);
- string years = Convert.ToString(year);
- string months = Convert.ToString(month);
- string days = Convert.ToString(day);
- if (months.Length == 4)
- {
- dt = Convert.ToDateTime(date);
- }
- else
- {
- string rq = "";
- if (years.Length == 1)
- {
- years = "0" + years;
- }
- if (months.Length == 1)
- {
- months = "0" + months;
- }
- if (days.Length == 1)
- {
- days = "0" + days;
- }
- rq = "20" + years + "-" + months + "-" + days;
- dt = Convert.ToDateTime(rq);
- }
- }
- catch
- {
- throw new Exception("日期格式不正确,转换日期类型失败!");
- }
- return dt;
- }
- /// <summary>
- /// 转化数字
- /// </summary>
- /// <param name="d">数字字符串</param>
- /// <returns></returns>
- public static decimal ConvertToDecimal(object d)
- {
- string dStr = (d ?? "").ToString();
- if (decimal.TryParse(dStr, out decimal result))
- {
- return result;
- }
- else
- {
- throw new Exception("数字格式不正确,转换数字类型失败!");
- }
- }
- /// <summary>
- /// 转化布尔
- /// </summary>
- /// <param name="b"></param>
- /// <returns></returns>
- public static bool ConvertToBoolen(object b)
- {
- string bStr = (b ?? "").ToString().Trim();
- if (bool.TryParse(bStr, out bool result))
- {
- return result;
- }
- else if (bStr == "0" || bStr == "1")
- {
- return (bStr == "0");
- }
- else
- {
- throw new Exception("布尔格式不正确,转换布尔类型失败!");
- }
- }
- #endregion
- }
- }
|