我获得了解析word文档表单并将其放入Excel工作表的任务。下面的代码可以很容易地做到这一点..但我最近了解到我需要将这些数据放入Excel表格而不仅仅是表格的单元格。
For row = 1 To theTable.Rows.Count `until end of rows
isHeaderOrNot = theTable.Cell(row, 0).Range.Text `if first field in row is a header
If isHeaderOrNot.Contains("Section") Or isHeaderOrNot.Contains("Field") Then Continue For
keyText = theTable.Cell(row, 2).Range.Text `gets key text
valueText = theTable.Cell(row, 3).Range.Text `gets value text
cleanStringKey = Regex.Replace(keyText, Chr(7), "") `clean strings
cleanStringValue = Regex.Replace(valueText, Chr(7), "")
xlWorkSheet.Cells(1, column) = cleanStringKey `puts key in row 1 and column n
xlWorkSheet.Cells(2, column) = cleanStringValue `puts value in row 2 column n
column = column + 1 `increment column
Next
我想知道我是否必须彻底改变我的代码才能使它成为一张桌子...简而言之从
开始要
我是VB.net的新手,所以如果可以的话,尽可能地减少所有内容。
答案 0 :(得分:2)
您可以使用Add
的WorkSheet.ListObject
方法创建新列表(表格)。
示例强>
添加对Microsoft.Office.Interop.Excel
的引用后,将此导入添加到表单:
Imports XL = Microsoft.Office.Interop.Excel
然后使用此类代码创建列表:
Dim Application = New XL.Application()
Application.Visible = True
Dim book = Application.Workbooks.Add()
Dim sheet = DirectCast(book.Worksheets(1), XL.Worksheet)
sheet.Cells(1, 1) = "Product"
sheet.Cells(1, 2) = "Price"
sheet.Cells(2, 1) = "Product 1"
sheet.Cells(2, 2) = "100"
sheet.Cells(3, 1) = "Product 2"
sheet.Cells(3, 2) = "200"
sheet.Cells(4, 1) = "Product 3"
sheet.Cells(4, 2) = "300"
Dim list = sheet.ListObjects.Add( _
XL.XlListObjectSourceType.xlSrcRange, _
sheet.Range(sheet.Cells(1, 1), sheet.Cells(4, 2)), _
Type.Missing, XL.XlYesNoGuess.xlYes)
然后你会看到这个结果: