您的位置:首页 > 其它

使用VSTO复制部分Excel单元格(带格式),粘贴并保存到另一Excel文件中

2009-04-23 15:13 661 查看
最近使用VSTO做了一个小项目,其中有一个需求是将一个Excel工作表中的很多个带格式的区域,分别另存到单独的Excel文件中,要求保留源格式。
虽然需求很简单,但也有几个技术点要搞明白:
1.带格式复制,但只复制值和格式,不复制公式,引用,校验等等。
2.另存为Excel
第一个问题,开始我以为很简单,直接使用选择性粘贴,粘贴所有就行了,其实不是那么简单。开始使用如下代码:

ws.get_Range(beginCell, pasteRange).PasteSpecial

(Microsoft.Office.Interop.Excel.XlPasteType.xlPasteAll,

Microsoft.Office.Interop.Excel.XlPasteSpecialOperation.xlPasteSpecialOperationNone,

Type.Missing, Type.Missing);

但发现复制出来的只是所有的值,格式都未复制出来。于是对Microsoft.Office.Interop.Excel.XlPasteType进行研究,发现有十几个选项,逐个试验,发现单独使用任何一个枚举都不能满足我的要求。后来灵机一动,使用了两次复制解决问题,一次复制值,一次复制格式!代码如下:

ws.get_Range(beginCell, pasteRange).PasteSpecial

(Microsoft.Office.Interop.Excel.XlPasteType.xlPasteValues,

Microsoft.Office.Interop.Excel.XlPasteSpecialOperation.xlPasteSpecialOperationNone,

Type.Missing, Type.Missing);
ws.get_Range(beginCell, pasteRange).PasteSpecial

(Microsoft.Office.Interop.Excel.XlPasteType.xlPasteFormats,

Microsoft.Office.Interop.Excel.XlPasteSpecialOperation.xlPasteSpecialOperationNone,

Type.Missing, Type.Missing);

再说第二个问题,也不难,主要是不同的对象模型使用的保存方法不同(前面的wb对象是Microsoft.Office.Interop.Excel.Workbook对象,之前实验过使用Microsoft.Office.Interop.Excel.ApplicationClass),经试验,Workbook对象的SaveCopyAs方法非常理想,因为它不会弹出任何对话框,自动覆盖之前存在的同名文件。
下面列出完整代码:

void creatCommand_Click(Microsoft.Office.Core.CommandBarButton Ctrl, ref bool

CancelDefault)
public static void CreatAndPaste(Excel.Application app,string pasteRange,string beginCell,string fileName)
{
//使用新的Excel进程添加一个新的工作簿
Microsoft.Office.Interop.Excel.Workbook wb = app.Workbooks.Add(Type.Missing);
Excel.Worksheet ws = (Excel.Worksheet)wb.Worksheets[1];

//粘贴
ws.get_Range(beginCell, pasteRange).PasteSpecial(Microsoft.Office.Interop.Excel.XlPasteType.xlPasteValues, Microsoft.Office.Interop.Excel.XlPasteSpecialOperation.xlPasteSpecialOperationNone, Type.Missing, Type.Missing);
ws.get_Range(beginCell, pasteRange).PasteSpecial(Microsoft.Office.Interop.Excel.XlPasteType.xlPasteFormats, Microsoft.Office.Interop.Excel.XlPasteSpecialOperation.xlPasteSpecialOperationNone, Type.Missing, Type.Missing);
ws.get_Range(beginCell, pasteRange).Columns.AutoFit();

//保存
wb.SaveCopyAs(fileName);

//关闭工作簿
Clipboard.Clear();
wb.Close(false, Type.Missing, Type.Missing);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: