深度优先

这个家伙好懒,除了文章什么都没留下

0%

【NPOI】Execl常用操作

引入库:

1
2
3
4
5
6
using NPOI.HSSF.UserModel;
using NPOI.HPSF;
using NPOI.POIFS.FileSystem;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using System.IO

冻结列

1
2
3
HSSFRow row1 = (HSSFRow)sheet.CreateRow(0);
row1.CreateCell(0).SetCellValue("冻结列");
sheet.CreateFreezePane(5, 0, 5, 0);//(冻结几列,冻结几行,从哪列开始显示(>=冻结列数),从哪行开始显示(>=冻结行数))

插入图片

1
2
3
4
5
6
7
8
byte[] bytes = System.IO.File.ReadAllBytes(@"D:\12345.jpg");
int pictureIdx = hssfworkbook.AddPicture(bytes, NPOI.SS.UserModel.PictureType.JPEG);
HSSFPatriarch patriarch = (HSSFPatriarch)sheet.CreateDrawingPatriarch();
//add a picture
HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 1023, 0, 0, 0, 4, 5); //后四个参数分别是c1,r1,c2,r2(c2为下标)(r2为实际行数)
HSSFPicture pict = (HSSFPicture)patriarch.CreatePicture(anchor, pictureIdx);
//显示图片原始大小
//pict.Resize();

设置超链接

1
2
3
4
5
6
7
8
9
10
//设置显示文本
cell.SetCellValue("链接");
//建一个HSSFHyperlink实体,指明链接类型为URL
//HSSFHyperlink link = new HSSFHyperlink(HyperlinkType.URL);
//link.Address = "http://www.baidu.com ";//给HSSFHyperlink的地址赋值

//链接当前文档中
HSSFHyperlink link = new HSSFHyperlink(HyperlinkType.DOCUMENT);
link.Address = (lsExpExcelSheetName1+"!A1");//当前文档的路径
cell.Hyperlink = link;//将链接方式赋值给单元格的Hyperlink即可将链接附加到单元格上

设置下拉框

1
2
3
4
5
6
string[] a = {"itemA", "itemB", "itemC"};//下拉框中的值
cell = (HSSFCell)row.CreateCell(6);
CellRangeAddressList regions = new CellRangeAddressList(4, 4+i, 6, 6);//(r1,r2,c1,c2)(全部参数都是下标)
DVConstraint constraint = DVConstraint.CreateExplicitListConstraint(a);
HSSFDataValidation dataValidate = new HSSFDataValidation(regions, constraint);
sheet.AddValidationData(dataValidate);

批注

单个批注

单个批注,只能创建一个,多个会显示错误,被覆盖

1
2
3
4
5
HSSFPatriarch patr1 = sheet.CreateDrawingPatriarch() as         HSSFPatriarch;
HSSFComment comment1 = patr1.CreateCellComment(new HSSFClientAnchor(0, 0, 0, 0, 1, 3, 3, 7)) as HSSFComment;
comment1.String = new HSSFRichTextString("作者:\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0");
HSSFCell hssfcell1 = sheet.CreateRow(10).CreateCell(10) as HSSFCell;
hssfcell1.CellComment=comment1;

循环创建批注

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
HSSFPatriarch patr =(HSSFPatriarch)sheet.CreateDrawingPatriarch();
CreationHelper facktory = hssfworkbook.GetCreationHelper();
Comment comment = null;
ClientAnchor anchor = null;
for (int i = 10; i < 20; i++)
{
Cell cell1 = row.CreateCell(i);
cell1.SetCellValue(i);
anchor = facktory.CreateClientAnchor();
anchor.Col1 = cell1.ColumnIndex;
anchor.Col2 = cell1.ColumnIndex + 1;
anchor.Row1 = row.RowNum;
anchor.Row2 = row.RowNum + 3;
comment = patr.CreateCellComment(anchor);
comment.String = new HSSFRichTextString(i.ToString());
comment.Author = ("nice");
cell1.CellComment = (comment);
}

设置单元格样式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
HSSFCellStyle cellStyle = (HSSFCellStyle)hssfworkbook.CreateCellStyle();
if (borderType.Length > 0)
{
//设置单元格边框样式
cellStyle.BorderBottom = NPOI.SS.UserModel.CellBorderType.THIN;
cellStyle.BorderLeft = NPOI.SS.UserModel.CellBorderType.THIN;
cellStyle.BorderRight = NPOI.SS.UserModel.CellBorderType.THIN;
cellStyle.BorderTop = NPOI.SS.UserModel.CellBorderType.THIN;
//设置单元格背景颜色
//cellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.GOLD.index;
cellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.GREY_40_PERCENT.index;
cellStyle.FillPattern = FillPatternType.SOLID_FOREGROUND;
}

//设置数字类型格式
cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("0.00");

//设置单元格字体
HSSFFont font = (HSSFFont)hssfworkbook.CreateFont();
font.Color = 200;//设置字体颜色
font.FontHeight = fontSize;//设置字体大小
font.FontName = "宋体";//宋体
font.IsItalic = false;//是否是斜体
font.IsStrikeout = false;//是否有中间线
//font.Underline = (byte)FontUnderlineType.DOUBLE;//设置下划线
font.FontHeightInPoints = fontSize;
//设置水平对齐
if (fontBold == "1")
font.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.BOLD;
if (fontAlign == "CENTER")
cellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.CENTER;
else if (fontAlign == "RIGHT")
cellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.RIGHT;
else
cellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.LEFT;
//设置垂直对齐
cellStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.CENTER;

cellStyle.WrapText = true;
cellStyle.SetFont(font);
return cellStyle;

ExeclHelper

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
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.Linq;
using System.Threading.Tasks;
using static NPOI.HSSF.Util.HSSFColor;

namespace Helpers
{
public class ExcelHelper
{
public static string DataToExcel(DataTable dt, List<ExportDataColumn> columnTitle, string title, string path)
{
XSSFWorkbook book = new XSSFWorkbook();
XSSFSheet sheet = book.CreateSheet("Export") as XSSFSheet;

CellRangeAddress region = new CellRangeAddress(0, 0, 0, columnTitle.Count - 1);
sheet.AddMergedRegion(region);

IFont font12 = book.CreateFont();
font12.FontHeightInPoints = 12;
font12.FontName = "微软雅黑";
font12.Boldweight = short.MaxValue;
font12.Color = Black.Index;

ICellStyle cellStyle = book.CreateCellStyle();
cellStyle.Alignment = HorizontalAlignment.Center;
cellStyle.BorderBottom = BorderStyle.Thin;
cellStyle.BorderLeft = BorderStyle.Thin;
cellStyle.BorderRight = BorderStyle.Thin;
cellStyle.BorderTop = BorderStyle.Thin;
cellStyle.SetFont(font12);
cellStyle.FillBackgroundColor = BlueGrey.Index;

for (int i = region.FirstRow; i <= region.LastRow; i++)
{
IRow row = sheet.CreateRow(i);
for (int j = region.FirstColumn; j <= region.LastColumn; j++)
{
ICell singleCell = row.CreateCell((short)j);
singleCell.CellStyle = cellStyle;
}
}

IRow hrow = sheet.GetRow(0);
hrow.Height = 20 * 20;
ICell icellltop0 = hrow.GetCell(0);
icellltop0.CellStyle = cellStyle;
icellltop0.SetCellValue(title + "_" + DateTime.Now.ToString("yyyy-MM-dd"));

ICellStyle TitleStyle = book.CreateCellStyle();
TitleStyle.FillForegroundColor = PaleBlue.Index;
TitleStyle.FillPattern = FillPattern.SolidForeground;
TitleStyle.Alignment = HorizontalAlignment.Center;
TitleStyle.BorderBottom = BorderStyle.Thin;
TitleStyle.BorderLeft = BorderStyle.Thin;
TitleStyle.BorderRight = BorderStyle.Thin;
TitleStyle.BorderTop = BorderStyle.Thin;

IRow TitleRow = sheet.CreateRow(1);
TitleRow.Height = 20 * 15;
for (int i = 0; i < columnTitle.Count; i++)
{
ICell cell = TitleRow.CreateCell(i);
cell.CellStyle = TitleStyle;
cell.SetCellValue(columnTitle[i].Label);
sheet.SetColumnWidth(i, columnTitle[i].ColumnWidth);
}

for (int i = 0; i < dt.Rows.Count; i++)
{
IRow row = sheet.CreateRow(i + 2);
for (int j = 0; j < columnTitle.Count; j++)
{
row.CreateCell(j).SetCellValue(dt.Rows[i][columnTitle[j].Prop].ToString());
}
}

ICellStyle borStyle = book.CreateCellStyle();
borStyle.Alignment = HorizontalAlignment.Center;
borStyle.BorderBottom = BorderStyle.Thin;
borStyle.BorderLeft = BorderStyle.Thin;
borStyle.BorderRight = BorderStyle.Thin;
borStyle.BorderTop = BorderStyle.Thin;

for (int i = 1; i <= dt.Rows.Count + 1; i++)
{
IRow row = sheet.GetRow(i);
row.Height = 20 * 16;
for (int j = 0; j < columnTitle.Count; j++)
{
ICell singleCell = row.GetCell((short)j);
singleCell.CellStyle = borStyle;
}
}
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string fileName = title + DateTime.Now.ToString("yyyyMMddHHmmssff") + ".xlsx";
using (FileStream fsWrite = File.OpenWrite($"{path}//{fileName}"))
{
book.Write(fsWrite);
}
return fileName;
}

public MemoryStream ImportDcExceptionType(string filePath)
{
IWorkbook workbook = null;
FileStream fs;
using (fs = new FileStream(filePath, FileMode.Open))
{
if (filePath.EndsWith(".xlsx"))
{
workbook = new XSSFWorkbook(fs);
}
else if (filePath.EndsWith(".xls"))
{
workbook = new HSSFWorkbook(fs);
}
if (workbook != null)
{
ISheet sheet = workbook.GetSheetAt(0);
if (sheet != null)
{
int rowCount = sheet.LastRowNum;
for (int i = 1; i <= rowCount; i++)
{
IRow row = sheet.GetRow(i);
var value = row.GetCell(0)?.ToString();

ICellStyle cellStyle = workbook.CreateCellStyle();
cellStyle.FillForegroundColor = HSSFColor.Red.Index;
cellStyle.FillPattern = FillPattern.SolidForeground;
row.GetCell(0).CellStyle = cellStyle;
}
}
}
MemoryStream memoryStream = new MemoryStream();
workbook.Write(memoryStream);
workbook.Close();
return memoryStream;
}
}

public ICellStyle CellStyle { get; set; }
public ExeclTypeEnum ExeclType { get; set; }
public IWorkbook Workbook { get; set; }
public ISheet Sheet { get; set; }
public ICreationHelper Facktory { get; set; }
public IDrawing Drawing { get; set; }

public ExcelHelper(string filePath, int sheetIndex)
{
using (FileStream fs = new FileStream(filePath, FileMode.Open))
{
if (filePath.EndsWith(".xlsx"))
{
ExeclType = ExeclTypeEnum.XLSX;
Workbook = new XSSFWorkbook(fs);
CellStyle = Workbook.CreateCellStyle();
CellStyle.FillForegroundColor = IndexedColors.Red.Index;
CellStyle.FillPattern = FillPattern.SolidForeground;
}
else
{
ExeclType = ExeclTypeEnum.XLS;
Workbook = new HSSFWorkbook(fs);
CellStyle = Workbook.CreateCellStyle();
CellStyle.FillForegroundColor = HSSFColor.Red.Index;
CellStyle.FillPattern = FillPattern.SolidForeground;
}
}
Sheet = Workbook.GetSheetAt(sheetIndex);
Facktory = Workbook.GetCreationHelper();
Drawing = Sheet.CreateDrawingPatriarch();
}

public void MarkError(IRow row, int indexCell, string msg)
{
ICell cell = row.GetCell(indexCell);
if (cell is null)
{
cell = row.CreateCell(indexCell);
}
IClientAnchor anchor = Facktory.CreateClientAnchor();

var comment = Drawing.CreateCellComment(anchor);
comment.Author = "Mr.Guan";

if (ExeclTypeEnum.XLSX == ExeclType)
{
anchor.Col1 = cell.ColumnIndex;
anchor.Col2 = cell.ColumnIndex + 1;
anchor.Row1 = row.RowNum;
anchor.Row2 = row.RowNum + 3;
comment.String = new XSSFRichTextString(msg);
}
else if (ExeclTypeEnum.XLS == ExeclType)
{
anchor.Col1 = cell.ColumnIndex;
anchor.Col2 = cell.ColumnIndex + 3;
anchor.Row1 = row.RowNum;
anchor.Row2 = row.RowNum + 5;
comment.String = new HSSFRichTextString(msg);
}
cell.CellComment = comment;
cell.CellStyle = CellStyle;
}
}

public enum ExeclTypeEnum
{
XLSX = 0,
XLS = 1
}

public class ExportDataColumn
{
public string Prop { get; set; }
public string Label { get; set; }
public int ColumnWidth { get; set; }
}
}