天修改一个用Excel的报表,有一个数据格是跨两列,一般单格的数据格用自动换行就可以实现自适应高度,但是跨列是不行的.查找google良久,也没发现适合的办法,一阵头痛之后,突然有了灵感,于是马上做试验,还真的实现了.先写出来,如果有困于这个问题的朋友偶然路过,或许还能有一点用处.
原理:在另外一个sheet里面利用单元格换行和自适应高度的特性,将一个 试验单元格宽度设置成 实际跨列单元格的宽度,然后将需要输入的字符放入该 试验单元格,取得高度返回给 实际跨列单元格就可以了.
以下是vb的代码
Private Sub Command1_Click()
Dim objExcel As New Excel.Application
Dim wkSheet As Excel.Worksheet
objExcel.Workbooks.Open "E:/book1.xls"
Set wkSheet = Worksheets("Sheet1") wkSheet.Select Dim iWidth As Double iWidth = wkSheet.Columns("A:A").ColumnWidth + wkSheet.Columns("B:B").ColumnWidth Set wkSheet = Worksheets("Sheet2") wkSheet.Select wkSheet.Columns("A:A").ColumnWidth = iWidth Range("A1").Select With Selection .HorizontalAlignment = xlGeneral .VerticalAlignment = xlCenter .WrapText = True .Orientation = 0 .AddIndent = False .IndentLevel = 0 .ShrinkToFit = False .ReadingOrder = xlContext .MergeCells = False End With ActiveCell.Value = "dsfsdafsdafasfsdafsadfdsafsdafa" Dim iHeight As Double iHeight = ActiveCell.RowHeight
Set wkSheet = Worksheets("Sheet1") wkSheet.Select Range("A1:B1").Select With Selection .HorizontalAlignment = xlGeneral .VerticalAlignment = xlCenter .WrapText = True .Orientation = 0 .AddIndent = False .IndentLevel = 0 .ShrinkToFit = False .ReadingOrder = xlContext .MergeCells = True End With Rows("1:1").Select Selection.RowHeight = iHeight Range("A1:B1").Select ActiveCell.Value = "dsfsdafsdafasfsdafsadfdsafsdafa" objExcel.ActiveWorkbook.SaveAs "e:/book2.xls" objExcel.AlertBeforeOverwriting = False objExcel.Quit End Sub
本文由来源 21aspnet,由 javajgs_com 整理编辑,其版权均为 21aspnet 所有,文章内容系作者个人观点,不代表 Java架构师必看 对观点赞同或支持。如需转载,请注明文章来源。