组件:Spire.Office for .NET
原Word文档:
第一步:添加引用组件
具体代码演示:
第二步:将数据导入从Word文档中导入到System.Data.DataTable对象中
- DocX document = DocX.Load("E:\\Program Files\\data.docx");
- //获取文档的第一个表格
- Table table = document.Tables[0];
- //创建一个Datable对象并命名为order
- DataTable dt = new DataTable("order");
- //将word表格中的数据导入Datable
- DataColumn column;
- for (int i = 0; i < table.ColumnCount; i++)
- {
- column = new DataColumn();
- column.ColumnName = table.Rows[0].Cells[i].Paragraphs[0].Text;
- dt.Columns.Add(column);
- }
- DataRow newRow;
- for (int i = 1; i < table.RowCount; i++)
- {
- newRow = dt.NewRow();
- Row row = table.Rows[i];
- for (int j = 0; j < table.ColumnCount; j++)
- {
- newRow[j] = row.Cells[j].Paragraphs[0].Text;
- }
- dt.Rows.Add(newRow);
- }
第三步,创建一个Workbook对象,并将dataTable插入到Workbook中,然后将文件保存为.xlsx文件
- //创建一个Workbook示例
- Workbook workbook = new Workbook();
- //新建一个空的worksheet
- workbook.CreateEmptySheets(1);
- //获取第一个worksheet
- Worksheet sheet = workbook.Worksheets[0];
- //将dataTable中的数据插入到worksheet中,1代表第一行和第一列
- sheet.InsertDataTable(dt, true, 1, 1);
- //保存文件
- workbook.SaveToFile("Data.xlsx",ExcelVersion.Version2007);
全部代码如下:
- using System.Data;
- using Spire.Xls;
- using Novacode; //Docx
- namespace word_table_to_excel
- {
- class Program
- {
- static void Main(string[] args)
- {
- DocX document = DocX.Load("E:\\Program Files\\data.docx");
- Table table = document.Tables[0];
- DataTable dt = new DataTable("order");
- DataColumn column;
- for (int i = 0; i < table.ColumnCount; i++)
- {
- column = new DataColumn();
- column.ColumnName = table.Rows[0].Cells[i].Paragraphs[0].Text;
- dt.Columns.Add(column);
- }
- DataRow newRow;
- for (int i = 1; i < table.RowCount; i++)
- {
- newRow = dt.NewRow();
- Row row = table.Rows[i];
- for (int j = 0; j < table.ColumnCount; j++)
- {
- newRow[j] = row.Cells[j].Paragraphs[0].Text;
- }
- dt.Rows.Add(newRow);
- }
- Workbook workbook = new Workbook();
- workbook.CreateEmptySheets(1);
- Worksheet sheet = workbook.Worksheets[0];
- sheet.InsertDataTable(dt, true, 1, 1);
- workbook.SaveToFile("Data.xlsx", ExcelVersion.Version2007);
- }
- }
- }