2013-05-09 160 views
6

有什麼辦法將我有一些表格的Word文檔轉換爲Excel文件? 轉換表格會很有幫助。使用OpenXML將Word docx轉換爲Excel

類似的東西:使用OpenXML的

  • 找到所有表的XML標籤
  • 複製XML標籤
    • 打開Word文檔
    • 創建Excel文件
    • 插入XML標籤與表從Word到新Excel文件

    我的意思是

    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 
    } 
    

    回答

    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逗號delmiated:

    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> 
    
    +0

    不幸的是,我需要類似的功能,但使用OpenXML – 2013-05-22 08:35:08