2013-05-09 44 views
6

Có cách nào để chuyển đổi tài liệu Word nơi tôi có một số bảng vào tệp Excel không? Sẽ rất hữu ích khi chuyển đổi bảng.Chuyển đổi Word docx sang Excel bằng OpenXML

Something như thế:

  • mở tài liệu Word sử dụng OpenXML
  • Tìm tất cả các bảng xml-thẻ
  • Sao chép xml-thẻ
  • Tạo tập tin Excel
  • Chèn xml-thẻ với bảng từ tệp Word sang Excel mới

Ý tôi là

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 
} 

Trả lời

1

để có được tất cả các bảng trong file docx bạn có thể sử dụng đoạn mã sau:

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 
      } 

     } 
    } 
} 

Và để viết chúng vào một file excel bạn phải làm điều này cho mỗi tế bào:

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

và cuối cùng là chức năng excel như sau:

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

Ngoài ra, bạn có thể sử dụng định dạng CSV hoặc HTML để tạo tệp excel. để làm điều đó chỉ đơn giản là tạo một file example.xlsx với nội dung này cho CSV dấu phẩy delmiated:

col1, col2, col3, col4 \ n

VAL1, VAL2, val3val4 \ n

hoặc trong Định dạng 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

Thật không may, tôi cần chức năng tương tự nhưng sử dụng OpenXML –

Các vấn đề liên quan