如何使用.NET将Word中的格式化单元格复制到Word中的表格单元格? [英] How to copy a formatted cell in Excel to a table cell in Word using .NET?

查看:282
本文介绍了如何使用.NET将Word中的格式化单元格复制到Word中的表格单元格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将Excel 2003(或2007)电子表格中的单元格复制到Word 2003(或2007)表中。我希望代码与版本无关,因此使用后期绑定。需要保留Excel单元格内容的格式,如颜色,下划线,贯穿。我的方法是使用Word文档作为模板。它在顶部有一个表,我可以复制到文档的末尾,根据需要添加行,并使用excel电子表格中的数据填充单词表格单元格。不幸的是,所有的格式都消失了。我所得到的只是文本本身。

I'm attempting to copy cells, one at a time, from an Excel 2003 (or 2007) spreadsheet to a Word 2003 (or 2007) table. I'd like the code to be version-agnostic, and so am using late binding. The formatting of the contents of the Excel cell, such as color, underline, strike-through, needs to be preserved. My approach is to use a Word doc as a template. It has a table at the top which I can copy to the end of the doc, add rows as needed, and fill in the word table cells with the data from the excel spreadsheet. Unfortunately, all the formatting disappears. All I get is the text itself.

推荐答案

原来比预期更容易。

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

这篇关于如何使用.NET将Word中的格式化单元格复制到Word中的表格单元格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆