excel - Excel 工作表中的数据表

标签 excel vb.net ms-word spreadsheet

我的任务是解析一个 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

我想知道我是否必须完全更改我的代码才能使它成为一个表格......简而言之

enter image description here



enter image description here

我对 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)

然后你会看到这个结果:

enter image description here

关于excel - Excel 工作表中的数据表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40896529/

相关文章:

javascript - Node.js:创建了存储在变量中的 xlsx 文件,但不确定如何保存它

vb.net - 添加端口到 Ping

mysql - 消除 ListView 中的日期时间

c# - 如何使用 C# 在 Excel 中查找并替换单词/短语

vba - 在 Excel VBA 中,根据列数据创建新行

vba - 错误替换双引号而不是双角引号 VBA Word

c# - MS Word 查看器 C# .NET 自动化

c# - 在 C# 中打开之前检查 Word 文档是否已经打开

vba - 在漫长的过程中如何通知用户?

c# - F# 中是否有 C# 和 VB 兼容的 System.Void*? (关闭指向非托管 Alloc 的指针?)