使用ClosedXml读取Excel遇到的问题总结(VB.NET)
使用ClosedXml源码生成的DLL,再导入到作业工程中(Imports ClosedXml.Excel)
本次使用的是打开Excel模板文件的方式,生成新的Excel文件
1.定义
打开工作簿
Dim xlBook As XLWorkbook = New XLWorkbook("Excel模板文件路径")
打开对应的Sheet,Sheet的位置是从0开始的
Dim xlSheet As IXLWorksheet = New xlBook.Worksheets(0)
模板显示页面的设置
标准 —> Normal
分页预览 —> PageBreakPreview
页面布局 —> PageLayout
xlSheet.SheetView.View = XLSheetViewOptions.PageBreakPreview
2.Cell的赋值
警告:
2.1.模板中对应的单元格跟赋值的类型相匹配的话,单元格不需要设置Format,
否则的话需要设置Format,正确的显示数据。
2.2.单元格赋值时,尽量保证赋值一次,如果赋值两次或大于两次,打开生成的Excel文件
可能会报错误(大概是文件损坏,不能打开,强行打开数据丢失之类的)
设置单元格表现形式
日期类型
xlSheet.Cell(RowIndex, ColumnIndex).Style.NumberFormat.Format = "YY/MM/DD"
xlSheet.Cell(RowIndex, ColumnIndex).Value = "20/07/05"
文字列类型
xlSheet.Cell(RowIndex, ColumnIndex).Style.NumberFormat.Format = "@"
xlSheet.Cell(RowIndex, ColumnIndex).Value = "TEST"
自定义类型
例:
Format —> #,###0.0
Format —> #,###0.00
Format —> #,###0.000
Format —> #,###0.0000
Format —> “”(标准类型)
xlSheet.Cell(RowIndex, ColumnIndex).Style.NumberFormat.Format = "#,###0.00"
xlSheet.Cell(RowIndex, ColumnIndex).Value = "2,000.00"
3.设置单元格的Style
复制行的类型
xlSheet.Row(FromRowIndex).CopyTo(xlSheet.Row(ToRowIndex))
插入新的一行,需要给新行设置Style
xlTempSheet.Row(RowIndex).InsertRowsAbove(1)
xlTempSheet.Range("单元格的范围").CopyTo("单元格的范围")
设置行的字体
xlSheet.Rows(RowIndex).Style.Font.FontColor = XLColor.Red
xlSheet.Rows(RowIndex).Style.Font.Italic = True
设置单元格的字体
xlSheet.Cell(RowIndex, ColumnIndex).Style.Font.FontColor = Excel.XLColor.Red
xlSheet.Cell(RowIndex, ColumnIndex).Style.Font.Italic = True
设置范围的边框
Dim range As Excel.IXLRange = xlSheet.Range("A5:AR12")
range.Style.Border.DiagonalBorder = Excel.XLBorderStyleValues.None
range.Style.Border.TopBorder = Excel.XLBorderStyleValues.Thin
range.Style.Border.LeftBorder = Excel.XLBorderStyleValues.Thin
range.Style.Border.RightBorder = Excel.XLBorderStyleValues.Thin
range.Style.Border.BottomBorder = Excel.XLBorderStyleValues.Thin
range.Style.Border.InsideBorder = Excel.XLBorderStyleValues.Thin
设置单元格文本的显示方向(显示出来单元格的方向值是-90度)
xlSheet.Cell(RowIndex, ColumnIndex).Style.Alignment.Horizontal = Excel.XLAlignmentHorizontalValues.Center
xlSheet.Cell(RowIndex, ColumnIndex).Style.Alignment.Vertical = Excel.XLAlignmentVerticalValues.Center
xlSheet.Cell(RowIndex, ColumnIndex).Style.Alignment.WrapText = False
xlSheet.Cell(RowIndex, ColumnIndex).Style.Alignment.TextRotation = 180
4.单元格中插入图片
Dim returnValue As Drawings.IXLPicture
'添加图片
returnValue = xlSheet.AddPicture("图片文件")
'图片放入的位置
returnValue.MoveTo(xlSheet.Cell(40, 36))
'计算图片的大小(根据实际情况设置数值,0.45的值在模板中占据了4*5的单元格中)
returnValue.Scale(0.45)
5.其他
第4行中从第一列到第10列进行合并
Dim xlTarget As Excel.IXLRange = xlSheet1.Range(xlSheet1.Cell(4, 1), xlSheet1.Cell(4, 10))
xlTarget.Merge()
取得Sheet中当前使用的最后一行的行号
Dim count_1 = xlSheet.LastRowUsed().RowNumber()
V列删除,以后的列往前自动移一格
xlSheet.Column("V").Delete()
设置Sheet的显示/隐藏
xlSheet.Visibility = Excel.XLWorksheetVisibility.VeryHidden
多个Sheet时,文件打开显示哪个Sheet
xlBook.Worksheet(1).TabActive = True