Data to Table in Excel Sheet

不想你离开。 提交于 2021-01-29 04:30:49

问题


I was given the assignment of parsing a word document form, and putting it into an Excel sheet. 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.

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.


回答1:


You can use Add method of WorkSheet.ListObject to create a new list (table).

Example

After adding reference to Microsoft.Office.Interop.Excel Add this import to the form:

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:



来源:https://stackoverflow.com/questions/40896529/data-to-table-in-excel-sheet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!