2013-05-09 13 views
6

C'è un modo per convertire un documento Word in cui ho alcune tabelle in un file Excel? Sarebbe molto utile convertire le tabelle.Converti Word docx in Excel usando OpenXML

Qualcosa del genere:

  • Aprire il documento Word utilizzando OpenXML
  • Trova tutte le tabelle XML-tag
  • Copia XML-tag
  • Creare file Excel
  • Inserire XML-tag con tavolo da Word a nuovo file Excel

Intendo

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 
} 

risposta

1

per ottenere tutte le tabelle nel file docx è possibile utilizzare il codice qui sotto:

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 
      } 

     } 
    } 
} 

E per scriverli in un file Excel che devi fare questo per ogni cella:

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(); 

infine funzione excel è la seguente:

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

Inoltre è possibile utilizzare il formato CSV o HTML per creare un file excel. per farlo è sufficiente creare un file example.xlsx con questo contenuto per CSV virgola delmiated:

col1, col2, col3, col4 \ n

val1, val2, val3val4 \ n

o in Formato 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

Sfortunatamente, ho bisogno di una funzione simile ma usando OpenXML –

Problemi correlati