简体   繁体   English

在VSTO加载项C#中保存Excel工作簿

[英]Save Excel Workbook in VSTO Addin C#

I've coded an Excel Addin which, when a button is pressed, changes the content of some cells. 我编写了一个Excel插件,当按下按钮时,它会更改某些单元格的内容。 Now I wanted to add the functionality to save the workbook to a new file after these replacements took place. 现在,我想添加一些功能,以便在进行这些替换后将工作簿保存到新文件中。

Here is my go at it and somehow this doesn't quite work like I imagined. 这是我的努力,这在某种程度上并不像我想象的那样有效。

This is the code to save the file in my ThisAddIn.cs: 这是将文件保存在我的ThisAddIn.cs中的代码:

public static void saveasnewfile()
        {
            Globals.ThisAddIn.Application.ActiveWorkbook.SaveCopyAs(@"C:\XXXX.XLS");
        }

And this is how I call this function (say when a button is pressed): 这就是我调用此函数的方式(例如,按下按钮时):

//...
ThisAddIn.saveasnewfile();
//...

Now when I press said button I get this error message: 现在,当我按下所说的按钮时,我收到此错误消息:

Microsoft Excel cannot access the file 'C:\\XXXX.XLS'. Microsoft Excel无法访问文件'C:\\ XXXX.XLS'。 There are several possible reasons: 有几种可能的原因:

• The file name or path does not exist. •文件名或路径不存在。 • The file is being used by another program. •该文件正在被另一个程序使用。 • The workbook you are trying to save has the samename as a currently open workbook. •您要保存的工作簿与当前打开的工作簿具有相同的名称。

Which seems kind of strange to me. 这对我来说有点奇怪。 Of course the file does not exist, since I want to create it... 当然文件不存在,因为我要创建它...

So what am I missing here? 那我在这里想念什么?

I would like to add the functionality to prompt the user for a path with a savefiledialog later. 我想添加功能,以便稍后提示用户输入带有savefiledialog的路径。 So some tips there would help as well :) 所以那里的一些技巧也会有所帮助:)

SOLUTION: 解:

For anyone that might stumble on the same thing, here is how I implemented it with the SaveFileDialog : 对于可能偶然发现同一件事的任何人,这是我使用SaveFileDialog实现它的方式:

var saveDialog = new SaveFileDialog() //create new instance of savefiledialog
{  
    Title = "Save As", //sets title of dialog box
    Filter = "Excel Worbook (*.xlsx)|*.xlsx", //filter for .xlsx files
    AddExtension = true, //automatically adds the .xlsx extension
    CheckPathExists = true //checks if the given path really exists
}

if (saveDialog.ShowDialog() == DialogResult.OK)
{
Globals.ThisAddIn.Application.ActiveWorkbook.SaveCopyAs(saveDialog.FileName);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM