1 需要引用的DLL

2 调用示例
public static void WriteExcel()
{
string templateFile = @"F:\12312\excel.xlsx";
string outFile = @"F:\12312\" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".xlsx";
string picPath = @"F:\12312\test.jpg";
IWorkbook workbook = ExcelHelper.GetReadWorkbook(templateFile);
ISheet sheet = workbook.GetSheetAt(0);
try
{
ExcelHelper.SetCellValue(sheet, 20, 0, "这里是第1行第1列内容");
ExcelHelper.SetCellValue(sheet, 0, 1, "这里是第1行第2列内容");
ExcelHelper.SetCellValue(sheet, 1, 0, "这里是第2行第1列内容");
ExcelHelper.SetCellValue(sheet, 1, 1, "这里是第2行第2列内容");
sheet.GetRow(1).Height = 44 * 20;
sheet.SetColumnWidth(1, 50 * 256);
ExcelHelper.SetCellValue(sheet, 2, 0, "这里是第3行第1列内容,需要设置字体样式");
ExcelHelper.SetCellRangeAddress(sheet, 2, 5, 0, 3);
ExcelHelper.AddRengionBorder(workbook, sheet, 2, 5, 0, 3);
var bitmap = (Bitmap)Image.FromFile("1.bmp");
ExcelHelper.InsertImage(workbook, sheet, 7, 16, 0, 2, bitmap);
ExcelHelper.Save(workbook, outFile);
Process.Start(outFile);
}
catch (Exception ex)
{
throw ex;
}
}
3 工具类
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.XSSF.UserModel;
namespace Demo_Excel
{
public class ExcelHelper
{
public static IWorkbook GetReadWorkbook(string filename)
{
FileStream fs = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
IWorkbook workbook;
string fileExt = Path.GetExtension(filename).ToLower();
switch (fileExt)
{
case ".xlsx":
workbook = new XSSFWorkbook(fs);
break;
case ".xls":
workbook = new HSSFWorkbook(fs);
break;
default:
throw new Exception("不支持的文件类型");
}
fs.Close();
return workbook;
}
public static IWorkbook GetWriteWorkbook(string filename)
{
if (string.IsNullOrWhiteSpace(filename))
throw new Exception("不支持的文件类型");
string fileExt = Path.GetExtension(filename).ToLower();
switch (fileExt)
{
case ".xlsx": return new XSSFWorkbook();
case ".xls": return new HSSFWorkbook();
default: throw new Exception("不支持的文件类型");
}
}
public static void Save(IWorkbook workbook, string filename)
{
MemoryStream stream = new MemoryStream();
workbook.Write(stream);
var buf = stream.ToArray();
using (FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write))
{
fs.Write(buf, 0, buf.Length);
fs.Flush();
fs.Close();
}
}
public static int UpdataExcel(string sourcefile, string outfile, int sheetIndex, Dictionary<string, string> dictionary)
{
var allKeys = dictionary.Keys.ToArray();
IWorkbook workbook = GetReadWorkbook(sourcefile);
ISheet sheet = workbook.GetSheetAt(sheetIndex);
int endRow = sheet.LastRowNum;
for (int i = 0; i < endRow; i++)
{
var row = sheet.GetRow(i);
for (int j = 0; j < row.LastCellNum; j++)
{
var data = GetCellString(row.GetCell(j));
if (allKeys.Contains(data))
{
row.Cells[j].SetCellValue(dictionary[data]);
}
}
}
Save(workbook, outfile);
return 0;
}
public static int UpdataExcel(string sourcefile, string outfile, int sheetIndex, Dictionary<Point, string> dictionary)
{
IWorkbook workbook = GetReadWorkbook(sourcefile);
ISheet sheet = workbook.GetSheetAt(sheetIndex);
foreach (var key in dictionary.Keys)
{
SetCellValue(sheet, key.X, key.Y, dictionary[key]);
}
Save(workbook, outfile);
return 0;
}
public static int Write(string fileName, DataTable data, string sheetName, bool isColumnWritten)
{
try
{
IWorkbook workbook = GetWriteWorkbook(fileName);
ISheet sheet = workbook.CreateSheet(sheetName);
int count = 0;
if (isColumnWritten)
{
IRow rowHeader = sheet.CreateRow(count++);
for (int i = 0; i < data.Columns.Count; i++)
{
ICell cell = rowHeader.CreateCell(i);
cell.SetCellValue(data.Columns[i].ColumnName);
}
}
for (int i = 0; i < data.Rows.Count; i++)
{
IRow rowData = sheet.CreateRow(count++);
for (int j = 0; j < data.Columns.Count; j++)
{
ICell cell = rowData.CreateCell(j);
cell.SetCellValue(data.Rows[i][j].ToString());
}
}
Save(workbook, fileName);
return count;
}
catch (Exception ex)
{
return -1;
}
}
public static int Write(string fileName, DataTable data, bool isColumnWritten)
{
int ret = Write(fileName, data, "Sheet1", isColumnWritten);
return ret;
}
public static int Write(string fileName, DataTable data)
{
int ret = Write(fileName, data, true);
return ret;
}
public static int Read(string fileName, int sheetIndex, bool isFirstRowCellName, out DataTable data)
{
data = new DataTable();
try
{
IWorkbook workbook = GetReadWorkbook(fileName);
ISheet sheet = workbook.GetSheetAt(sheetIndex);
if (isFirstRowCellName)
{
IRow firstRow = sheet.GetRow(0);
var list = ReadDataRow(firstRow);
data.Columns.AddRange(list.Select(t => new DataColumn(t)).ToArray());
}
else
{
int nMaxCol = 0;
for (int i = 0; i < sheet.LastRowNum; i++)
{
nMaxCol = Math.Max(nMaxCol, sheet.GetRow(i).LastCellNum);
}
for (int i = 0; i < nMaxCol; i++)
{
data.Columns.Add($"列{i + 1}");
}
}
int startRow = !isFirstRowCellName ? 0 : 1;
int endRow = sheet.LastRowNum;
var ret2 = Read(sheet, startRow, endRow, ref data);
if (ret2 < 0) return -1;
return data.Rows.Count;
}
catch (Exception ex)
{
throw ex;
}
}
public static int Read(string fileName, string sheetName, bool isFirstRowCellName, out DataTable data)
{
data = new DataTable();
try
{
IWorkbook workbook = GetReadWorkbook(fileName);
ISheet sheet = workbook.GetSheet(sheetName);
Console.WriteLine(sheet.SheetName);
if (isFirstRowCellName)
{
IRow firstRow = sheet.GetRow(0);
var list = ReadDataRow(firstRow);
data.Columns.AddRange(list.Select(t => new DataColumn(t)).ToArray());
}
else
{
int nMaxCol = 0;
for (int i = 0; i < sheet.LastRowNum; i++)
{
nMaxCol = Math.Max(nMaxCol, sheet.GetRow(i).LastCellNum);
}
for (int i = 0; i < nMaxCol; i++)
{
data.Columns.Add($"列{i + 1}");
}
}
int startRow = !isFirstRowCellName ? 0 : 1;
int endRow = !isFirstRowCellName ? 0 : 1;
var ret = Read(sheet, startRow, endRow, ref data);
if (ret < 0)
return -1;
return data.Rows.Count;
}
catch (Exception ex)
{
return -1;
}
}
public static int Read(string fileName, bool isFirstRowCellName, out DataTable data)
{
int ret = Read(fileName, "sheet1", isFirstRowCellName, out data);
return ret;
}
public static int Read(string fileName, out DataTable data)
{
int ret = Read(fileName, "sheet1", false, out data);
return ret;
}
public static int Read(ISheet sheet, int startRow, int endRow, ref DataTable data)
{
endRow += 1;
for (int i = startRow; i < endRow; i++)
{
var sheetRow = sheet.GetRow(i);
if (sheetRow == null)
{
data.Rows.Add();
}
else
{
var list = ReadDataRow(sheetRow);
var row = data.NewRow();
int count = Math.Min(list.Count, data.Columns.Count);
for (int j = 0; j < count; j++)
{
row[j] = list[j];
}
data.Rows.Add(row);
}
}
return data.Rows.Count;
}
public static List<string> ReadDataRow(ISheet sheet, int index) => ReadDataRow(sheet.GetRow(index));
public static List<string> ReadDataRow(IRow row)
{
List<string> result = null;
if (row != null)
{
result = new List<string>();
int startColumn = 0;
int endColumn = row.LastCellNum;
for (int i = startColumn; i < endColumn; i++)
{
result.Add(GetCellString(row.GetCell(i)));
}
}
return result;
}
public static void InsertImage(IWorkbook workbook, ISheet sheet, int firstRow, int lastRow, int firstCell, int lastCell, Bitmap bitmap)
{
byte[] imgBytes = BitmapToBytes(bitmap);
int pictureIdx = workbook.AddPicture(imgBytes, PictureType.PNG);
if (workbook is XSSFWorkbook)
{
XSSFDrawing patriarch = (XSSFDrawing)sheet.CreateDrawingPatriarch();
XSSFClientAnchor anchor = new XSSFClientAnchor(10, 10, 0, 0, firstCell, firstRow, lastCell, lastRow);
XSSFPicture pict = (XSSFPicture)patriarch.CreatePicture(anchor, pictureIdx);
}
else
{
HSSFPatriarch patriarch = (HSSFPatriarch)sheet.CreateDrawingPatriarch();
HSSFClientAnchor anchor = new HSSFClientAnchor(10, 10, 0, 0, firstCell, firstRow, lastCell, lastRow);
HSSFPicture pict = (HSSFPicture)patriarch.CreatePicture(anchor, pictureIdx);
}
}
public static void SetCellValue(ISheet sheet, int rowIndex, int cellIndex, string value)
{
if (sheet.GetRow(rowIndex) == null)
{
sheet.CreateRow(rowIndex);
}
if (sheet.GetRow(rowIndex).GetCell(cellIndex) == null)
{
sheet.GetRow(rowIndex).CreateCell(cellIndex);
}
sheet.GetRow(rowIndex).GetCell(cellIndex).SetCellValue(value);
}
public static void SetCellRangeAddress(ISheet sheet, int rowstart, int rowend, int colstart, int colend)
{
for (int r = rowstart; r <= rowend; r++)
{
for (int c = colstart; c <= colend; c++)
{
if (sheet.GetRow(r) == null)
{
sheet.CreateRow(r);
}
if (sheet.GetRow(r).GetCell(c) == null)
{
sheet.GetRow(r).CreateCell(c);
}
}
}
CellRangeAddress cellRangeAddress = new CellRangeAddress(rowstart, rowend, colstart, colend);
sheet.AddMergedRegion(cellRangeAddress);
}
public static void AddRengionBorder(IWorkbook workbook, 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;
cell = sheet.GetRow(i).GetCell(n);
if (cell == null)
{
cell = sheet.GetRow(i).CreateCell(n);
}
ICellStyle style = sheet.Workbook.CreateCellStyle();
style.BorderTop = BorderStyle.Thin;
style.BorderBottom = BorderStyle.Thin;
style.BorderLeft = BorderStyle.Thin;
style.BorderRight = BorderStyle.Thin;
style.Alignment = HorizontalAlignment.Center;
style.VerticalAlignment = VerticalAlignment.Center;
if (i == firstRow)
{
style.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Black.Index;
style.FillPattern = FillPattern.SolidForeground;
IFont font = workbook.CreateFont();
font.Color = NPOI.HSSF.Util.HSSFColor.White.Index;
font.FontHeightInPoints = 18;
style.SetFont(font);
}
cell.CellStyle = style;
}
}
}
private static byte[] BitmapToBytes(Bitmap bitmap)
{
MemoryStream ms = new MemoryStream();
bitmap.Save(ms, ImageFormat.Bmp);
ms.Seek(0, SeekOrigin.Begin);
byte[] bytes = new byte[ms.Length];
ms.Read(bytes, 0, bytes.Length);
ms.Dispose();
return bytes;
}
private static string GetCellString(ICell cell)
{
if (cell != null)
{
switch (cell.CellType)
{
case CellType.Unknown:
return "";
case CellType.Numeric:
return cell.NumericCellValue.ToString();
case CellType.String:
return cell.StringCellValue;
case CellType.Formula:
return cell.CellFormula;
case CellType.Blank:
return "";
case CellType.Boolean:
return cell.BooleanCellValue.ToString();
case CellType.Error:
return "";
default:
return "";
}
}
else
{
return "";
}
}
}
}