简体   繁体   中英

Data to Table in Excel Sheet

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.

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:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM