将 Interop 与 C# 一起使用,Excel 保存更改原始文件。如何否定这个?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29141/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using Interop with C#, Excel Save changing original. How to negate this?
提问by Chad Boyer
The problem: Loading an excel spreadsheet template. Using the Save command with a different filename and then quitting the interop object. This ends up saving the original template file. Not the result that is liked.
问题:加载 Excel 电子表格模板。使用具有不同文件名的 Save 命令,然后退出互操作对象。这最终会保存原始模板文件。不是喜欢的结果。
public void saveAndExit(string filename)
{
excelApplication.Save(filename);
excelApplication.Quit();
}
Original file opened is c:\testing\template.xls The file name that is passed in is c:\testing\7777 (date).xls
打开的原文件是c:\testing\template.xls 传入的文件名是c:\testing\7777(日期).xls
Does anyone have an answer?
有人有答案吗?
(The answer I chose was the most correct and thorough though the wbk.Close() requires parameters passed to it. Thanks.)
(虽然 wbk.Close() 需要传递给它的参数,但我选择的答案是最正确和最彻底的。谢谢。)
采纳答案by Kevin Crumley
Excel interop is pretty painful. I dug up an old project I had, did a little fiddling, and I think this is what you're looking for. The other commenters are right, but, at least in my experience, there's a lot more to calling SaveAs() than you'd expect if you've used the same objects (without the interop wrapper) in VBA.
Excel 互操作非常痛苦。我挖出了一个我有的旧项目,做了一些摆弄,我认为这就是你要找的。其他评论者是对的,但是,至少根据我的经验,如果您在 VBA 中使用了相同的对象(没有互操作包装器),那么调用 SaveAs() 比您预期的要多得多。
Microsoft.Office.Interop.Excel.Workbook wbk = excelApplication.Workbooks[0]; //or some other way of obtaining this workbook reference, as Jason Z mentioned
wbk.SaveAs(filename, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, XlSaveAsAccessMode.xlNoChange,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing);
wbk.Close();
excelApplication.Quit();
Gotta love all those Type.Missings. But I think they're necessary.
一定要喜欢所有那些 Type.Missings。但我认为它们是必要的。
回答by Joel Lucsy
Have you tried the SaveAs from the Worksheet?
您是否尝试过工作表中的另存为?
回答by Jason Z
Rather than using an ExcelApplication, you can use the Workbook object and call the SaveAs() method. You can pass the updated file name in there.
您可以使用 Workbook 对象并调用 SaveAs() 方法,而不是使用 ExcelApplication。您可以在那里传递更新的文件名。
回答by Rad
- Ditto on the SaveAs
- Whenever I have to do Interop I create a separate VB.NET class library and write the logic in VB. It is just not worth the hassle doing it in C#
- 同上另存为
- 每当我必须进行互操作时,我都会创建一个单独的 VB.NET 类库并在 VB 中编写逻辑。在 C# 中这样做是不值得的