我的任务是解析一个 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 完全陌生,所以如果可以的话,尽可能地把所有东西都简化一下。
最佳答案
您可以使用 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)
然后你会看到这个结果:
关于excel - Excel 工作表中的数据表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40896529/