[英]Data to Table in Excel Sheet
I was given the assignment of parsing a word document form, and putting it into an Excel sheet. 我被分配了解析Word文档格式并将其放入Excel工作表的任务。 The code below does that with ease.. but I've recently learned I need to put that data into an Excel table instead of just the cells of a sheet. 下面的代码很容易做到这一点..但是我最近了解到我需要将数据放入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
I was wondering if I would have to completely change my code in order to make it a table... In short go from 我想知道是否必须完全更改我的代码才能使其成为表格...总之
To 至
I am completely new to VB.net so if you could, dumb everything down as much as possible. 我对VB.net完全陌生,因此,如果可能的话,请尽可能使所有内容变得愚蠢。
You can use Add
method of WorkSheet.ListObject
to create a new list (table). 您可以使用WorkSheet.ListObject
Add
方法创建一个新列表(表)。
Example 例
After adding reference to Microsoft.Office.Interop.Excel
Add this import to the form: 添加对Microsoft.Office.Interop.Excel
引用后,将此导入添加到表单:
Imports XL = Microsoft.Office.Interop.Excel
Then use such code to create a list: 然后使用这样的代码创建一个列表:
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)
Then you will see this result: 然后,您将看到以下结果:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.