123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185 |
- using NPOI.HSSF.UserModel;
- using NPOI.SS.Formula.Eval;
- using NPOI.SS.UserModel;
- using NPOI.SS.Util;
- using NPOI.XSSF.UserModel;
- using System;
- using System.Collections.Generic;
- using System.Data;
- using System.IO;
- using System.Text;
- namespace AIPlatform.Protocol.Utilities
- {
- /// <summary>
- /// 单元格
- /// </summary>
- public class MergedRegion
- {
- /// <summary>
- /// 起始行
- /// </summary>
- public int FirstRow { get; set; }
- /// <summary>
- /// 结束行
- /// </summary>
- public int LastRow { get; set; }
- /// <summary>
- /// 起始列
- /// </summary>
- public int FirstCol { get; set; }
- /// <summary>
- /// 结束列
- /// </summary>
- public int LastCol { get; set; }
- }
- public class ExcelHelper
- {
- private IWorkbook _workbook = null;
- private FileStream _fs = null;
- private bool _disposed;
- public ExcelHelper()
- {
- _disposed = false;
- }
- /// <summary>
- /// 将DataTable数据导入到excel中
- /// </summary>
- /// <param name="data">要导入的数据</param>
- /// <param name="isColumnWritten">DataTable的列名是否要导入</param>
- /// <param name="sheetName">要导入的excel的sheet的名称</param>
- /// <returns>导入数据行数(包含列名那一行)</returns>
- public int DataTableToExcel(string _fileName, DataTable data, string sheetName, bool isColumnWritten)
- {
- _fs = new FileStream(_fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
- if (_fileName.IndexOf(".xlsx", StringComparison.Ordinal) > 0) // 2007版本
- _workbook = new XSSFWorkbook();
- else if (_fileName.IndexOf(".xls", StringComparison.Ordinal) > 0) // 2003版本
- _workbook = new HSSFWorkbook();
- try
- {
- ISheet sheet = null;
- if (_workbook != null)
- {
- sheet = _workbook.CreateSheet(sheetName);
- }
- else
- {
- return -1;
- }
- var count = 0;
- var j = 0;
- 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;
- }
- var i = 0;
- for (i = 0; i < data.Rows.Count; ++i)
- {
- IRow row = sheet.CreateRow(count);
- for (j = 0; j < data.Columns.Count; ++j)
- {
- row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString());
- }
- ++count;
- }
- _workbook.Write(_fs); //写入到excel
- return count;
- }
- catch (Exception ex)
- {
- Logger.WriteLineError("DataTable to excel failed: " + ex.Message);
- return -1;
- }
- }
- /// <summary>
- /// 将excel中的数据导入到DataTable中
- /// </summary>
- /// <param name="sheetName">excel工作薄sheet的名称</param>
- /// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param>
- /// <returns>返回的DataTable</returns>
- public DataTable ExcelToDataTable(string _fileName, string sheetName = "Sheet1", bool isFirstRowColumn = true)
- {
- DataTable data = new DataTable();
- try
- {
- _fs = new FileStream(_fileName, FileMode.Open, FileAccess.Read);
- if (_fileName.IndexOf(".xlsx", StringComparison.Ordinal) > 0) // 2007版本
- _workbook = new XSSFWorkbook(_fs);
- else if (_fileName.IndexOf(".xls", StringComparison.Ordinal) > 0) // 2003版本
- _workbook = new HSSFWorkbook(_fs);
- ISheet sheet = null;
- 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的编号 即总的列数
- var startRow = 0;
- if (isFirstRowColumn)
- {
- for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
- {
- ICell cell = firstRow.GetCell(i);
- if (cell != null)
- {
- string cellValue = cell.StringCellValue.Trim();
- 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 || row.FirstCellNum < 0) 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().Trim();
- }
- data.Rows.Add(dataRow);
- }
- }
- return data;
- }
- catch (Exception ex)
- {
- Logger.WriteLineError("Excel to dataTable failed: " + ex);
- return null;
- }
- }
- public DataTable ExcelToDataTable(string _fileName, out string productName, string sheetName = "Sheet1", bool isFirstRowColumn = true)
- {
- productName = string.Empty;
- DataTable data = new DataTable();
- try
- {
- _fs = new FileStream(_fileName, FileMode.Open, FileAccess.Read);
- if (_fileName.IndexOf(".xlsx", StringComparison.Ordinal) > 0) // 2007版本
- _workbook = new XSSFWorkbook(_fs);
- else if (_fileName.IndexOf(".xls", StringComparison.Ordinal) > 0) // 2003版本
- _workbook = new HSSFWorkbook(_fs);
- ISheet sheet = null;
- 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的编号 即总的列数
- productName = firstRow.GetCell(4).StringCellValue;
- var startRow = 0;
- if (isFirstRowColumn)
- {
- for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
- {
- ICell cell = firstRow.GetCell(i);
- if (cell != null)
- {
- string cellValue = cell.StringCellValue.Trim();
- 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 || row.FirstCellNum < 0) 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().Trim();
- }
- data.Rows.Add(dataRow);
- }
- }
- return data;
- }
- catch (Exception ex)
- {
- Logger.WriteLineError("Excel to dataTable failed: " + ex);
- return null;
- }
- }
- /// <summary>
- /// 将Excel中的数据导入到DataTable中
- /// </summary>
- /// <param name="_fileName">文件名</param>
- /// <param name="colNames">列名</param>
- /// <param name="categorties">分类</param>
- /// <param name="sheetName">工作表名</param>
- /// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param>
- /// <returns></returns>
- public DataTable ExcelToDataTable(string _fileName, out List<string> colNames, out List<string> categorties, string sheetName = "Sheet1", bool isFirstRowColumn = true)
- {
- colNames = new List<string>();
- categorties = new List<string>();
- DataTable data = new DataTable();
- try
- {
- _fs = new FileStream(_fileName, FileMode.Open, FileAccess.Read);
- if (_fileName.IndexOf(".xlsx", StringComparison.Ordinal) > 0) // 2007版本
- _workbook = new XSSFWorkbook(_fs);
- else if (_fileName.IndexOf(".xls", StringComparison.Ordinal) > 0) // 2003版本
- _workbook = new HSSFWorkbook(_fs);
- ISheet sheet = null;
- 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的编号 即总的列数
- var startRow = 0;
- if (isFirstRowColumn)
- {
- for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
- {
- ICell cell = firstRow.GetCell(i);
- if (cell != null)
- {
- string cellValue = cell.StringCellValue.Trim();
- if (cellValue != null)
- {
- DataColumn column = new DataColumn(cellValue);
- data.Columns.Add(column);
- colNames.Add(cellValue);
- }
- }
- }
- 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 || row.FirstCellNum < 0) 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().Trim();
- //获取分类
- var font = row.GetCell(j).CellStyle.GetFont(_workbook);
- if (!string.IsNullOrEmpty(dataRow[j].ToString()) && font.IsItalic && font.IsBold) //字体加粗、斜体默认为分类
- {
- categorties.Add(dataRow[j].ToString());
- }
- }
- }
- data.Rows.Add(dataRow);
- }
- }
- return data;
- }
- catch (Exception ex)
- {
- Logger.WriteLineError("Excel to dataTable failed: " + ex);
- return null;
- }
- }
- public DataTable ExcelToDataTableByStream(Stream fileStream, string sheetName = "Sheet1", bool isFirstRowColumn = true)
- {
- DataTable data = new DataTable();
- try
- {
- if (fileStream == null)
- {
- return data;
- }
- _workbook = new XSSFWorkbook(fileStream);
- ISheet sheet = null;
- 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的编号 即总的列数
- var startRow = 0;
- if (isFirstRowColumn)
- {
- for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
- {
- ICell cell = firstRow.GetCell(i);
- if (cell != null)
- {
- string cellValue = cell.StringCellValue.Trim();
- 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 || row.FirstCellNum < 0) 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().Trim();
- }
- }
- data.Rows.Add(dataRow);
- }
- }
- return data;
- }
- catch (Exception ex)
- {
- Logger.WriteLineError("ProductSpecExcelToDataTableByStream failed: " + ex);
- return null;
- }
- }
- /// <summary>
- /// 写值
- /// </summary>
- /// <param name="sheet">工作表</param>
- /// <param name="row">行号,从1计</param>
- /// <param name="column">列号,从1计</param>
- /// <param name="value"></param>
- /// <param name="isWrapText">自动换行</param>
- /// <param name="heightInPoints">行高</param>
- /// <param name="IsCenter">居中</param>
- public void SetValue(ISheet sheet, int row, int column, string value, bool isWrapText = false, int heightInPoints = 20, bool IsCenter = false, bool fontName = false)
- {
- row -= 1;
- IRow xrow = sheet.GetRow(row);
- if (xrow == null)
- {
- xrow = sheet.CreateRow(row);
- }
- //行高
- xrow.HeightInPoints = heightInPoints;
- column -= 1;
- var cell = xrow.GetCell(column);
- if (cell == null)
- {
- cell = xrow.CreateCell(column);
- }
- if (IsCenter)
- {
- cell.CellStyle.Alignment = HorizontalAlignment.Center;//居中
- }
- if (fontName)
- {
- }
- //设置单元格内容换行
- if (isWrapText)
- {
- cell.CellStyle.WrapText = true;
- }
- cell.SetCellValue(value ?? string.Empty);
- }
- public void SetStyleValue(ISheet sheet, int row, int column, string value, XSSFWorkbook book, bool isWrapText = false, int heightInPoints = 20, bool IsCenter = false, string strValue = null, string descriptionEnglish = null)
- {
- row -= 1;
- IRow xrow = sheet.GetRow(row);
- if (xrow == null)
- {
- xrow = sheet.CreateRow(row);
- }
- //行高
- xrow.HeightInPoints = heightInPoints;
- column -= 1;
- var cell = xrow.GetCell(column);
- if (cell == null)
- {
- cell = xrow.CreateCell(column);
- }
- if (IsCenter)
- {
- cell.CellStyle.Alignment = HorizontalAlignment.Center;//居中
- }
- IFont font2 = book.CreateFont(); ;
- font2.Color = IndexedColors.Black.Index;
- font2.FontName = "黑体";
- font2.FontHeightInPoints = (short)10;
- var rts1 = new XSSFRichTextString(strValue + descriptionEnglish + value);
- if (!string.IsNullOrEmpty(strValue + descriptionEnglish + value))
- {
- IFont monthFont = book.CreateFont();
- monthFont.FontHeightInPoints = 11;
- monthFont.FontName = "黑体";
- monthFont.Boldweight = (short)FontBoldWeight.Bold;
- if (!string.IsNullOrEmpty(strValue))
- rts1.ApplyFont(0, strValue.Length - 1, monthFont);
- if (!string.IsNullOrEmpty(descriptionEnglish))
- rts1.ApplyFont(strValue.Length, (strValue + descriptionEnglish).Length - 1, monthFont);
- if (!string.IsNullOrEmpty(value))
- rts1.ApplyFont((strValue + descriptionEnglish).Length, (strValue + value + descriptionEnglish).Length - 1, font2);
- }
- if (!string.IsNullOrEmpty(descriptionEnglish))
- {
- //设置单元格内容换行
- if (isWrapText)
- {
- cell.CellStyle.WrapText = true;
- }
- }
- cell.SetCellValue(rts1);
- // cell.SetCellValue(value);
- }
- /// <summary>
- /// 设置行高
- /// </summary>
- /// <param name="sheet"></param>
- /// <param name="row">行号,从1计</param>
- /// <param name="column">列号,从1计</param>
- /// <param name="width">行宽</param>
- public void SetHeightInPoints(ISheet sheet, int row, int column, string value = null, int width = 180, int height = 18)
- {
- row -= 1;
- IRow xrow = sheet.GetRow(row);
- if (xrow == null)
- {
- xrow = sheet.CreateRow(row);
- }
- column -= 1;
- var cell = xrow.GetCell(column);
- if (cell == null)
- {
- cell = xrow.CreateCell(column);
- }
- //设置单元格内容换行
- //cell.CellStyle.WrapText = true;
- #region 设置行高
- value = value ?? GetCellValue(cell).ToString();
- var heightInPoints = 0;
- var strVal = value.Split("\r\n".ToCharArray());
- foreach (var val in strVal)
- {
- var strVal2 = val.Split(new char[] { '\r', '\n' });
- foreach (var val2 in strVal2)
- {
- var length = Encoding.UTF8.GetBytes(val2).Length;
- heightInPoints += height * (length / width + 1);
- }
- }
- xrow.HeightInPoints = heightInPoints;
- #endregion
- if (!string.IsNullOrEmpty(value))
- {
- cell.SetCellValue(value);
- }
- }
- public void SetValue(ISheet sheet, int row, int column, double value, int heightInPoints = 20)
- {
- row -= 1;
- IRow xrow = sheet.GetRow(row);
- if (xrow == null)
- {
- xrow = sheet.CreateRow(row);
- }
- //行高
- xrow.HeightInPoints = heightInPoints;
- column -= 1;
- var cell = xrow.GetCell(column);
- if (cell == null)
- {
- cell = xrow.CreateCell(column);
- }
- cell.SetCellValue(value);
- }
- public void SetValueAndFormuar(ISheet sheet, int row, int column, string value, string formular = null)
- {
- row -= 1;
- IRow xrow = sheet.GetRow(row);
- if (xrow == null)
- {
- xrow = sheet.CreateRow(row);
- }
- column -= 1;
- var cell = xrow.GetCell(column);
- if (cell != null)
- {
- cell.SetCellValue(value);
- if (!string.IsNullOrEmpty(formular))
- {
- cell.SetCellType(CellType.Formula);
- cell.SetCellFormula(formular);
- }
- }
- else
- cell = xrow.CreateCell(column);
- }
- public void SetValueAndCellStyle(XSSFWorkbook book, ISheet sheet, int row, int column, string value, bool isBold = false, bool IsItalic = false, bool isFillBackgroundColor = false,
- bool isBorder = false, bool isWrapText = false, int heightInPoints = 20)
- {
- var cell = SetValueAndStyle(book, sheet, row, column, isBold, IsItalic, isFillBackgroundColor, isBorder, isWrapText, heightInPoints);
- //设置单元格内容
- cell.SetCellValue(value);
- }
- public void SetValueAndCellStyle(XSSFWorkbook book, ISheet sheet, int row, int column, double value, bool isBold = false, bool IsItalic = false, bool isFillBackgroundColor = false,
- bool isBorder = false, bool isWrapText = false, int heightInPoints = 20)
- {
- var cell = SetValueAndStyle(book, sheet, row, column, isBold, IsItalic, isFillBackgroundColor, isBorder, isWrapText, heightInPoints);
- //设置单元格内容
- cell.SetCellValue(value);
- }
- private ICell SetValueAndStyle(XSSFWorkbook book, ISheet sheet, int row, int column, bool isBold = false, bool IsItalic = false, bool isFillBackgroundColor = false,
- bool isBorder = false, bool isWrapText = false, int heightInPoints = 20)
- {
- //在工作表中:建立行,参数为行号,从1计
- row -= 1;
- IRow xrow = sheet.GetRow(row);
- if (xrow == null)
- {
- xrow = sheet.CreateRow(row);
- }
- //行高
- xrow.HeightInPoints = heightInPoints;
- //在行中:建立单元格,参数为列号,从1计
- column -= 1;
- var cell = xrow.GetCell(column);
- if (cell == null)
- {
- cell = xrow.CreateCell(column);
- var style = book.CreateCellStyle();
- //设置单元格的样式:
- cell.CellStyle.Alignment = HorizontalAlignment.Left;//左对齐
- cell.CellStyle.VerticalAlignment = VerticalAlignment.Center;//垂直居中
- var font = book.CreateFont();
- //字体
- font.FontName = "Calibri";
- //字体大小
- font.FontHeightInPoints = 12;
- //设置字体加粗样式
- font.IsBold = isBold;
- //斜体
- font.IsItalic = IsItalic;
- //使用SetFont方法将字体样式添加到单元格样式中
- style.SetFont(font);
- cell.CellStyle = style;
- }
- //背景色
- if (isFillBackgroundColor)
- {
- cell.CellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Yellow.Index;// 是设置前景色不是背景色
- cell.CellStyle.FillPattern = FillPattern.SolidForeground;
- }
- //加边框
- if (isBorder)
- {
- var style = book.CreateCellStyle();
- style.CloneStyleFrom(cell.CellStyle);
- style.BorderTop = BorderStyle.Thin;
- style.BorderRight = BorderStyle.Thin;
- style.BorderLeft = BorderStyle.Thin;
- style.BorderBottom = BorderStyle.Thin;
- cell.CellStyle = style;
- }
- //设置单元格内容换行
- cell.CellStyle.WrapText = isWrapText;
- return cell;
- }
- public void SetValueAndBackgroundColor(XSSFWorkbook book, ISheet sheet, int row, int column, string value, bool isFillBackgroundColor = true,
- int heightInPoints = 20, short color = NPOI.HSSF.Util.HSSFColor.Yellow.Index)
- {
- //在工作表中:建立行,参数为行号,从1计
- row -= 1;
- IRow xrow = sheet.GetRow(row);
- if (xrow == null)
- {
- xrow = sheet.CreateRow(row);
- }
- //行高
- xrow.HeightInPoints = heightInPoints;
- //在行中:建立单元格,参数为列号,从1计
- column -= 1;
- var cell = xrow.GetCell(column);
- if (cell == null)
- {
- cell = xrow.CreateCell(column);
- }
- //设置单元格的样式:背景色
- if (isFillBackgroundColor)
- {
- var style = book.CreateCellStyle();
- style.CloneStyleFrom(cell.CellStyle);
- style.FillForegroundColor = color;
- style.FillPattern = FillPattern.SolidForeground;
- cell.CellStyle = style;
- }
- //设置单元格内容换行
- cell.CellStyle.WrapText = true;
- //设置单元格内容
- cell.SetCellValue(value ?? string.Empty);
- }
- public void SetValueAndBackgroundColor(XSSFWorkbook book, ISheet sheet, int row, int column, double value, bool isFillBackgroundColor = true,
- int heightInPoints = 20, short color = NPOI.HSSF.Util.HSSFColor.Yellow.Index)
- {
- //在工作表中:建立行,参数为行号,从1计
- row -= 1;
- IRow xrow = sheet.GetRow(row);
- if (xrow == null)
- {
- xrow = sheet.CreateRow(row);
- }
- //行高
- xrow.HeightInPoints = heightInPoints;
- //在行中:建立单元格,参数为列号,从1计
- column -= 1;
- var cell = xrow.GetCell(column);
- if (cell == null)
- {
- cell = xrow.CreateCell(column);
- }
- //设置单元格的样式:背景色
- if (isFillBackgroundColor)
- {
- var style = book.CreateCellStyle();
- style.CloneStyleFrom(cell.CellStyle);
- style.FillForegroundColor = color;
- style.FillPattern = FillPattern.SolidForeground;
- cell.CellStyle = style;
- }
- //设置单元格内容换行
- cell.CellStyle.WrapText = true;
- //设置单元格内容
- cell.SetCellValue(value);
- }
- public void SetValue(XSSFWorkbook book, ISheet sheet, int row, int column, double value, bool isFillBackgroundColor, bool isMergedRegion, int heightInPoints = 20)
- {
- //在工作表中:建立行,参数为行号,从1计
- row -= 1;
- IRow xrow = sheet.GetRow(row);
- if (xrow == null)
- {
- xrow = sheet.CreateRow(row);
- }
- //行高
- xrow.HeightInPoints = heightInPoints;
- //在行中:建立单元格,参数为列号,从1计
- column -= 1;
- var cell = xrow.GetCell(column);
- if (cell == null)
- {
- cell = xrow.CreateCell(column);
- }
- //设置单元格的样式:背景色
- if (isFillBackgroundColor)
- {
- var style = book.CreateCellStyle();
- style.CloneStyleFrom(cell.CellStyle);
- style.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Yellow.Index;
- style.FillPattern = FillPattern.SolidForeground;
- cell.CellStyle = style;
- }
- //设置单元格内容
- cell.SetCellValue(value);
- //合并单元格
- if (isMergedRegion)
- {
- sheet.AddMergedRegion(new CellRangeAddress(row - 1, row, column, column));
- }
- }
- /// <summary>
- /// 合并单元格
- /// </summary>
- /// <param name="sheet"></param>
- /// <param name="row"></param>
- /// <param name="column"></param>
- /// <param name="value"></param>
- /// <param name="heightInPoints"></param>
- public void SetValueIsMergedRegion(ISheet sheet, int row, int column, string value, int heightInPoints, bool isMergedRegion = false)
- {
- //在工作表中:建立行,参数为行号,从1计
- row -= 1;
- IRow xrow = sheet.GetRow(row);
- if (xrow == null)
- {
- xrow = sheet.CreateRow(row);
- }
- //行高
- xrow.HeightInPoints = heightInPoints;
- //在行中:建立单元格,参数为列号,从1计
- column -= 1;
- var cell = xrow.GetCell(column);
- if (cell == null)
- {
- cell = xrow.CreateCell(column);
- }
- //设置单元格内容
- cell.SetCellValue(value);
- //合并单元格
- if (isMergedRegion)
- {
- sheet.AddMergedRegion(new CellRangeAddress(row - 1, row, column, column));
- }
- }
- public void SetValueIsMergedRegion(ISheet sheet, int row, int column, double value, int heightInPoints, bool isMergedRegion = false)
- {
- //在工作表中:建立行,参数为行号,从1计
- row -= 1;
- IRow xrow = sheet.GetRow(row);
- if (xrow == null)
- {
- xrow = sheet.CreateRow(row);
- }
- //行高
- xrow.HeightInPoints = heightInPoints;
- //在行中:建立单元格,参数为列号,从1计
- column -= 1;
- var cell = xrow.GetCell(column);
- if (cell == null)
- {
- cell = xrow.CreateCell(column);
- }
- //设置单元格内容
- cell.SetCellValue(value);
- //合并单元格
- if (isMergedRegion)
- {
- sheet.AddMergedRegion(new CellRangeAddress(row - 1, row, column, column));
- }
- }
- /// <summary>
- /// 获得行高
- /// </summary>
- /// <param name="value">值</param>
- /// <param name="width">行宽</param>
- /// <returns></returns>
- public int GetHeightInPoints(string value, int width = 40, int height = 20)
- {
- value = value ?? string.Empty;
- var length = 0;
- var heightInPoints = 0;
- var strVal = value.Split("\r\n".ToCharArray());
- foreach (var val in strVal)
- {
- var strVal2 = val.Split(new char[] { '\r', '\n' });
- foreach (var val2 in strVal2)
- {
- length = Encoding.UTF8.GetBytes(val2).Length + 3;
- heightInPoints += height * (length / width + 1);
- }
- }
- return heightInPoints;
- }
- /// <summary>
- /// 合并单元格
- /// </summary>
- /// <param name="sheet"></param>
- public void AddMergedRegion(ISheet sheet, MergedRegion mergedRegion)
- {
- mergedRegion.FirstRow--;
- mergedRegion.LastRow--;
- mergedRegion.FirstCol--;
- mergedRegion.LastCol--;
- sheet.AddMergedRegion(new CellRangeAddress(mergedRegion.FirstRow, mergedRegion.LastRow, mergedRegion.FirstCol, mergedRegion.LastCol));
- }
- /// <summary>
- /// XSSFRow Copy Command
- ///
- /// Description: Inserts a existing row into a new row, will automatically push down
- /// any existing rows. Copy is done cell by cell and supports, and the
- /// command tries to copy all properties available (style, merged cells, values, etc...)
- /// </summary>
- /// <param name="workbook"></param>
- /// <param name="worksheet"></param>
- /// <param name="sourceRowNum"></param>
- /// <param name="destinationRowNum"></param>
- public void CopyRow(XSSFWorkbook workbook, ISheet worksheet, int sourceRowNum, int destinationRowNum)
- {
- // Get the source / new row
- IRow newRow = worksheet.GetRow(destinationRowNum);
- IRow sourceRow = worksheet.GetRow(sourceRowNum);
- // If the row exist in destination, push down all rows by 1 else create a new row
- if (newRow != null)
- {
- worksheet.ShiftRows(destinationRowNum, worksheet.LastRowNum, 1);
- }
- else
- {
- newRow = worksheet.CreateRow(destinationRowNum);
- }
- // Loop through source columns to add to new row
- for (int i = 0; i < sourceRow.LastCellNum; i++)
- {
- // Grab a copy of the old/new cell
- ICell oldCell = sourceRow.GetCell(i);
- ICell newCell = newRow.CreateCell(i);
- // If the old cell is null jump to next cell
- if (oldCell == null)
- {
- newCell = null;
- continue;
- }
- // Copy style from old cell and apply to new cell
- var newCellStyle = workbook.CreateCellStyle();
- newCellStyle.CloneStyleFrom(oldCell.CellStyle); ;
- newCell.CellStyle = newCellStyle;
- // If there is a cell comment, copy
- if (newCell.CellComment != null) newCell.CellComment = oldCell.CellComment;
- // If there is a cell hyperlink, copy
- if (oldCell.Hyperlink != null) newCell.Hyperlink = oldCell.Hyperlink;
- // Set the cell data type
- newCell.SetCellType(oldCell.CellType);
- // Set the cell data value
- switch (oldCell.CellType)
- {
- case CellType.Blank:
- newCell.SetCellValue(oldCell.StringCellValue);
- break;
- case CellType.Boolean:
- newCell.SetCellValue(oldCell.BooleanCellValue);
- break;
- case CellType.Error:
- newCell.SetCellErrorValue(oldCell.ErrorCellValue);
- break;
- case CellType.Formula:
- //newCell.SetCellFormula(oldCell.CellFormula);
- var formula = $"H{destinationRowNum + 1}*I{destinationRowNum + 1}";
- newCell.SetCellFormula(formula);
- break;
- case CellType.Numeric:
- newCell.SetCellValue(oldCell.NumericCellValue);
- break;
- case CellType.String:
- newCell.SetCellValue(oldCell.RichStringCellValue);
- break;
- case CellType.Unknown:
- newCell.SetCellValue(oldCell.StringCellValue);
- break;
- }
- }
- // If there are are any merged regions in the source row, copy to new row
- for (int i = 0; i < worksheet.NumMergedRegions; i++)
- {
- CellRangeAddress cellRangeAddress = worksheet.GetMergedRegion(i);
- if (cellRangeAddress != null && cellRangeAddress.FirstRow == sourceRow.RowNum)
- {
- CellRangeAddress newCellRangeAddress = new CellRangeAddress(newRow.RowNum,
- (newRow.RowNum +
- (cellRangeAddress.FirstRow -
- cellRangeAddress.LastRow)),
- cellRangeAddress.FirstColumn,
- cellRangeAddress.LastColumn);
- worksheet.AddMergedRegion(newCellRangeAddress);
- }
- }
- }
- public DataTable GenerateData()
- {
- DataTable data = new DataTable();
- for (int i = 0; i < 5; ++i)
- {
- data.Columns.Add("Columns_" + i.ToString(), typeof(string));
- }
- for (int i = 0; i < 10; ++i)
- {
- DataRow row = data.NewRow();
- row["Columns_0"] = "item0_" + i.ToString();
- row["Columns_1"] = "item1_" + i.ToString();
- row["Columns_2"] = "item2_" + i.ToString();
- row["Columns_3"] = "item3_" + i.ToString();
- row["Columns_4"] = "item4_" + i.ToString();
- data.Rows.Add(row);
- }
- return data;
- }
- public void PrintData(DataTable data)
- {
- if (data == null) return;
- for (int i = 0; i < data.Rows.Count; ++i)
- {
- for (int j = 0; j < data.Columns.Count; ++j)
- Console.Write("{0} ", data.Rows[i][j]);
- Console.Write("\n");
- }
- }
- public new void Dispose()
- {
- Dispose(true);
- GC.SuppressFinalize(this);
- }
- protected virtual new void Dispose(bool disposing)
- {
- if (!this._disposed)
- {
- if (disposing)
- {
- _fs?.Close();
- }
- _fs = null;
- _disposed = true;
- }
- }
- /// <summary>
- /// 加范围边框
- /// </summary>
- /// <param name="firstRow">起始行</param>
- /// <param name="lastRow">结束行</param>
- /// <param name="firstCell">起始列</param>
- /// <param name="lastCell">结束列</param>
- /// <returns></returns>
- public void AddRengionBorder(XSSFWorkbook book, ISheet sheet, int firstRow, int lastRow, int firstCell, int lastCell)
- {
- for (int i = firstRow; i < lastRow; i++)
- {
- for (int n = firstCell; n < lastCell; n++)
- {
- ICell cell;
- if (sheet.GetRow(i) == null)
- continue;
- cell = sheet.GetRow(i).GetCell(n);
- if (cell == null)
- {
- cell = sheet.GetRow(i).CreateCell(n);
- cell.SetCellValue(" ");
- }
- var cellstyle = book.CreateCellStyle();
- //为首行加上方边框
- if (i == firstRow)
- {
- cellstyle.BorderTop = BorderStyle.Thin;//ss.UserModel.BorderStyle.THIN;
- }
- //为末行加下方边框
- if (i == lastRow - 1)
- {
- cellstyle.BorderBottom = BorderStyle.Thin;//ss.UserModel.BorderStyle.THIN;
- }
- //为首列加左边框
- if (n == firstCell)
- {
- cellstyle.BorderLeft = BorderStyle.Thin; //ss.UserModel.BorderStyle.THIN;
- }
- //为末列加右边框
- if (n == lastCell - 1)
- {
- cellstyle.BorderRight = BorderStyle.Thin; //ss.UserModel.BorderStyle.THIN;
- }
- cell.CellStyle = cellstyle;
- }
- }
- }
- /// <summary>
- /// 获取单元格的值
- /// </summary>
- /// <param name="item"></param>
- /// <returns></returns>
- public static object GetCellValue(ICell item)
- {
- if (item == null)
- {
- return string.Empty;
- }
- switch (item.CellType)
- {
- case CellType.Boolean:
- return item.BooleanCellValue;
- case CellType.Error:
- return ErrorEval.GetText(item.ErrorCellValue);
- case CellType.Formula:
- switch (item.CachedFormulaResultType)
- {
- case CellType.Boolean:
- return item.BooleanCellValue;
- case CellType.Error:
- return ErrorEval.GetText(item.ErrorCellValue);
- case CellType.Numeric:
- if (DateUtil.IsCellDateFormatted(item))
- {
- return item.DateCellValue.ToString("yyyy-MM-dd");
- }
- else
- {
- return item.NumericCellValue;
- }
- case CellType.String:
- string str = item.StringCellValue;
- if (!string.IsNullOrEmpty(str))
- {
- return str.ToString();
- }
- else
- {
- return string.Empty;
- }
- case CellType.Unknown:
- case CellType.Blank:
- default:
- return string.Empty;
- }
- case CellType.Numeric:
- if (DateUtil.IsCellDateFormatted(item))
- {
- return item.DateCellValue.ToString("yyyy-MM-dd");
- }
- else
- {
- return item.NumericCellValue;
- }
- case CellType.String:
- string strValue = item.StringCellValue;
- return strValue.ToString().Trim();
- case CellType.Unknown:
- case CellType.Blank:
- default:
- return string.Empty;
- }
- }
- }
- }
|