6

Is there any way to convert Word document where I have some tables into Excel file? It would be very helpful to convert tables.

Something like that:

  • Open Word document using OpenXML
  • Find all tables xml-tags
  • Copy xml-tags
  • Create Excel file
  • Insert xml-tags with table from Word to new Excel file

I mean

void OpenWordDoc(string filePath)
{
_documentWord = SpreadsheetDocument.Open(filePath, true);
}

List<string> GetAllTablesXMLTags()
{
//find and copy
}

List<string> CreateExcelFile(string filePath)
{
TemplateExcelDocument excelDocument = new TemplateExcelDocument();
_documentExcel = excelDocument.CreatePackage(filePath);
}

void InsertXmlTagsToExcelFile(string filePath)
{
CreateExcelFiles(filePath);
var xmlTable = GetAllTablesXMLTags();
// ... insert to _documentExcel
}
4

2 回答 2

2

你的步骤是正确的。

我想分享一些sdk文档,希望它可以在一定程度上有所帮助:

开放式 XML SDK 2.5 for Office

处理单词表时:

使用 WordprocessingML 表(Open XML SDK)

处理excel表格时:

使用共享字符串表 (Open XML SDK)

使用 SpreadsheetML 表(Open XML SDK)

于 2013-05-26T03:57:27.683 回答
1

要获取 docx 文件中的所有表,您可以使用以下代码:

using System;
using Independentsoft.Office;
using Independentsoft.Office.Word;
using Independentsoft.Office.Word.Tables;

namespace Sample
{
    class Program
    {
        static void Main(string[] args)
        {
            WordDocument doc = new WordDocument("c:\\test.docx");

            Table[] tables = doc.GetTables();

            foreach (Table table in tables)
            {
                //read data
            }

        }
    }
}

要将它们写入 excel 文件,您必须对每个单元格执行此操作:

 app.Visible = false;
        workbooks = app.Workbooks;
        workbook =  workbooks.Add(XlWBATemplate.xlWBATWorksheet);
        sheets = workbook.Worksheets;
        worksheet = (_Worksheet)sheets.get_Item(1);
        excel(row, column, "value");
        workbook.Saved = true;
        workbook.SaveAs(output_file);
        app.UserControl = false;
        app.Quit();

最后excel函数如下:

    public void excel(int row, int column, string value)
    {
        worksheet.Cells[row, column] = value;
    }

您也可以使用CSVHTML格式化来创建一个 excel 文件。example.xlsx为此,只需为 CSV 逗号分隔创建一个包含此内容的文件:

col1,col2,col3,col4 \n

val1,val2,val3val4 \n

或 HTML 格式:

<table>
 <tr>
  <td>col1</td>
  <td>col2</td>
  <td>col3</td>
 </tr>
 <tr>
  <td>val1</td>
  <td>val2</td>
  <td>val3</td>
 </tr>
</table>
于 2013-05-20T19:32:33.977 回答