2010-04-20 147 views
0

我試圖將Excel 2003(或2007)電子表格中的單元格一次一個地複製到Word 2003(或2007)表格中。我希望代碼是版本不可知的,所以我使用後期綁定。需要保留Excel單元格內容的格式,如顏色,下劃線,穿透。我的方法是使用Word文檔作爲模板。它在頂部有一個表格,我可以將其複製到文檔的末尾,根據需要添加行,並使用Excel電子表格中的數據填寫單詞表格單元格。不幸的是,所有的格式都消失了。我得到的只是文本本身。如何使用.NET將Excel中格式化的單元格複製到Word表格單元格中?

回答

1

想通了。結果比預期的更容易。

Dim appExcel As Excel.Application 
Dim thisWorkbook As Excel.Workbook 
Dim thisWorksheet As Excel.Worksheet 

appExcel = CType(CreateObject("Excel.Application"), Excel.Application) 
thisWorkbook = appExcel.Workbooks.Open("Excelfilename.xls") 
thisWorksheet = CType(thisWorkbook.ActiveSheet, Excel.Worksheet) 

Dim appWord As Word.Application 
Dim thisDoc As Word.Document 
Dim thisWordTable As Word.Table 

' Use a template word doc that has a table in it. 

appWord = CType(CreateObject("Word.Application"), Word.Application) 
thisDoc = appWord.Documents.OpenNoRepairDialog("templateWordFileName.doc") 
thisDoc.SaveAs("outputDocFileName.doc") 

' Get a reference to the table. 
thisWordTable = thisDoc.Tables(0) 

' Copy data from excel to this table. 
CType(thisWorksheet.Cells(5, 1), Excel.Range).Copy() 
thisWordTable.Cell(1, 2).Select() 
appWord.Selection.Paste() 

thisDoc.Save() 
thisDoc.Close() 
appWord.Quit() 

thisWorkbook.Close(False) ' Don't save any changes to workbook. 
appExcel.Quit() 
0

您可能必須首先執行文本,然後手動複製樣式。您可以使用Workbook.Styles獲取Microsoft.Office.Interop.Excel.Style的集合,然後應該能夠使用該數據創建Microsoft.Office.Interop.Word.Styles。

相關問題