Files
2025-12-11 14:04:39 +08:00

193 lines
6.6 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Data;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
namespace IotManager.Common
{
public class ExcelHelper
{
public static DataTable ReadExcelToDataTable(string filePath)
{
DataTable dataTable = new DataTable();
// 打开 Excel 文件
IWorkbook workbook;
using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
if (filePath.EndsWith(".xlsx"))
workbook = new XSSFWorkbook(fileStream); // 读取 .xlsx 文件
else if (filePath.EndsWith(".xls"))
workbook = new HSSFWorkbook(fileStream); // 读取 .xls 文件
else
throw new Exception("文件格式不支持,只支持 .xls 和 .xlsx");
}
// 读取第一个工作表
var sheet = workbook.GetSheetAt(0);
if (sheet == null)
throw new Exception("工作表为空!");
// 获取表头
var headerRow = sheet.GetRow(0);
if (headerRow == null)
throw new Exception("未找到表头行!");
for (int i = 0; i < headerRow.LastCellNum; i++)
{
var columnName = headerRow.GetCell(i)?.ToString() ?? $"Column{i}";
dataTable.Columns.Add(columnName);
}
// 读取数据行
for (int i = 1; i <= sheet.LastRowNum; i++) // 从第 1 行(索引为 1开始读取
{
var row = sheet.GetRow(i);
if (row == null) continue;
var dataRow = dataTable.NewRow();
for (int j = 0; j < row.LastCellNum; j++)
{
var cell = row.GetCell(j);
dataRow[j] = cell != null ? GetCellValue(cell) : DBNull.Value;
}
dataTable.Rows.Add(dataRow);
}
return dataTable;
}
static object GetCellValue(ICell cell)
{
switch (cell.CellType)
{
case CellType.Numeric:
return DateUtil.IsCellDateFormatted(cell) ? cell.DateCellValue : cell.NumericCellValue;
case CellType.String:
return cell.StringCellValue;
case CellType.Boolean:
return cell.BooleanCellValue;
case CellType.Formula:
return cell.CellFormula;
case CellType.Blank:
return string.Empty;
default:
return cell.ToString();
}
}
public void CreateNewExcel(string filePath, DataTable dataTable)
{
IWorkbook workbook;
if (filePath.EndsWith(".xlsx"))
workbook = new XSSFWorkbook(); // 创建 .xlsx 文件
else
workbook = new HSSFWorkbook(); // 创建 .xls 文件
var sheet = workbook.CreateSheet("Sheet1");
// 写入表头
var headerRow = sheet.CreateRow(0);
for (int i = 0; i < dataTable.Columns.Count; i++)
{
headerRow.CreateCell(i).SetCellValue(dataTable.Columns[i].ColumnName);
}
// 写入数据
for (int i = 0; i < dataTable.Rows.Count; i++)
{
var dataRow = sheet.CreateRow(i + 1);
for (int j = 0; j < dataTable.Columns.Count; j++)
{
dataRow.CreateCell(j).SetCellValue(dataTable.Rows[i][j].ToString());
}
}
// 保存文件
using (var stream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
workbook.Write(stream);
}
}
public void SetColumnWidthAndRowHeight(IWorkbook workbook, int sheetIndex, int columnIndex, int rowIndex)
{
var sheet = workbook.GetSheetAt(sheetIndex);
// 设置列宽(单位是 1/256 字符宽度)
sheet.SetColumnWidth(columnIndex, 20 * 256); // 设置第 1 列宽度为 20
// 设置行高(单位是点数)
var row = sheet.GetRow(rowIndex) ?? sheet.CreateRow(rowIndex);
row.HeightInPoints = 25; // 设置行高为 25 点
}
public void SetCellStyle(IWorkbook workbook, int sheetIndex, int rowIndex, int colIndex)
{
var sheet = workbook.GetSheetAt(sheetIndex);
var cell = sheet.GetRow(rowIndex).GetCell(colIndex) ?? sheet.GetRow(rowIndex).CreateCell(colIndex);
var style = workbook.CreateCellStyle();
// 设置字体
var font = workbook.CreateFont();
font.FontHeightInPoints = 12;
font.FontName = "Arial";
font.IsBold = true;
style.SetFont(font);
// 设置边框
style.BorderBottom = BorderStyle.Thin;
style.BorderLeft = BorderStyle.Thin;
style.BorderRight = BorderStyle.Thin;
style.BorderTop = BorderStyle.Thin;
// 设置背景颜色
style.FillForegroundColor = IndexedColors.LightBlue.Index;
style.FillPattern = FillPattern.SolidForeground;
cell.CellStyle = style;
cell.SetCellValue("示例文本");
}
public void FullExample(string filePath, DataTable dataTable)
{
IWorkbook workbook = filePath.EndsWith(".xlsx") ? (IWorkbook)new XSSFWorkbook() : new HSSFWorkbook();
var sheet = workbook.CreateSheet("Sheet1");
// 设置表头
var headerRow = sheet.CreateRow(0);
for (int i = 0; i < dataTable.Columns.Count; i++)
{
headerRow.CreateCell(i).SetCellValue(dataTable.Columns[i].ColumnName);
}
// 写入数据
for (int i = 0; i < dataTable.Rows.Count; i++)
{
var dataRow = sheet.CreateRow(i + 1);
for (int j = 0; j < dataTable.Columns.Count; j++)
{
dataRow.CreateCell(j).SetCellValue(dataTable.Rows[i][j].ToString());
}
}
// 设置列宽和行高
SetColumnWidthAndRowHeight(workbook, 0, 1, 1);
// 设置单元格样式
SetCellStyle(workbook, 0, 1, 1);
// 保存文件
using (var stream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
workbook.Write(stream);
}
}
}
}