1.新建workbook 不同版本,個人建議07以上為准。
public static IWorkbook Create(ExcelVersion version = ExcelVersion.Excel07)
{
IWorkbook workbook = null;
switch (version)
{
case ExcelVersion.Excel03:
workbook = new HSSFWorkbook();
break;
case ExcelVersion.Excel07:
workbook = new XSSFWorkbook();
break;
default:
workbook = new XSSFWorkbook();
break;
}
return workbook;
}
模板也是可以創建的。
using (FileStream file = new FileStream(template, FileMode.Open, FileAccess.Read))
{
IWorkbook workbook = WorkbookFactory.Create(file);
return workbook;
}
workbook 可以創建多個sheet
var sheet = workbook.CreateSheet("invoice"); //參數是sheet name
sheet里面創建行
IRow headRow = sheet.CreateRow(rowIndex); //參數是int 型行號,默認從0開始
行里創建單元格
Row.CreateCell(0).SetCellValue("測試"); // 單元格賦值
2。是我本人遇到的一些樣式問題:
a.設置列寬
int[] columnWidth = new int[] { 5, 20, 20, 10, 8, 8, 8, 8 };
// 單位是1/256個字符寬度
if (columnWidth != null)
{
for (int i = 0; i < columnWidth.Length; i++)
{
sheet.SetColumnWidth(i, 256 * columnWidth[i]);
}
}
b.設置邊框 (都是以單元格為單位的)
//邊框樣式
ICellStyle style = workbook.CreateCellStyle();
style.BorderBottom = BorderStyle.Hair;
style.BorderLeft = BorderStyle.Hair;
style.BorderRight = BorderStyle.Hair;
style.BorderTop = BorderStyle.Hair;
//字體
NPOI.SS.UserModel.IFont font = workbook.CreateFont();
font.FontHeightInPoints = 8; //8號字 字號
font.FontName = "SimSun"; //宋體 字體
style.SetFont(font);
//加背景色
style.FillPattern = FillPattern.SolidForeground;
style.FillForegroundColor = HSSFColor.Teal.Index; //HSSFColor有顏色對照表可以參考的
上面只是一個style變量。
row.GetCell(0).CellStyle = style;
//某個單元格設置樣式
c.合並單元格
sheet.AddMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 0, 4)); //參數是firstRow index,LastRowIndex,firstColumnIndex,LastColumnIndex
d.設置行高和換行
row.Height = 9 * 20; //一定要乘以20,具體原因不記得了 設置 行高
//針對內容過長,需要換行,防止excel內容被遮擋。
// 獲取當前列寬度;
int columnWidth = sheet.GetColumnWidth(columnIndex) / 256;
//當前行
var currentRow = sheet.GetRow(rowIndex);
//當前單元格
var currentCell = currentRow.GetCell(columnIndex);
//當前單元格內容的長度
int length = currentCell.ToString().Length;
currentRow.Height = 20 * 20;
//內容換行
StringBuilder stringBuilder = new StringBuilder(currentRow.Cells[columnIndex].StringCellValue.Substring(0, 13) + "\n");
var appendString = currentRow.Cells[columnIndex].StringCellValue.Substring(13, length - 13);
stringBuilder.Append(appendString);
//設置換行
ICellStyle wrapStyle = workbook.CreateCellStyle();
wrapStyle.WrapText = true;
currentRow.Cells[columnIndex].CellStyle = wrapStyle;
最后加入圖片:
byte[] bytes = File.ReadAllBytes(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
VendorContext.Current.SealUrl));
int pictureIndex = workbook.AddPicture(bytes, PictureType.PNG);
var patriarch = sheet.CreateDrawingPatriarch();
XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 1023, 0, 1, rowIndex - 1, 3, rowIndex + 2);
var pict = patriarch.CreatePicture(anchor, pictureIndex);
pict.Resize();
//這塊圖片可能拉伸,注意XSSFClientAnchor的參數(大概是x y坐標之類的,反正多測試)
