创建并保存Excel文件

3
我有以下代码,可以在我的C#代码中创建一个新的Excel文件。当我尝试保存文件时,我希望用户选择保存的位置。
在方法#1中,我可以使用workbook SaveCopyAs保存文件,而不提示用户选择位置。这将在C:\Temp目录下保存一个文件。
方法#2将在我的Users\Documents文件夹中保存文件,然后提示用户选择位置并保存第二个副本。如何消除第一个副本保存在Users\Documents文件夹中的情况?
Excel.Application oXL;
Excel._Workbook oWB;
Excel._Worksheet oSheet;
Excel.Range oRng;

try
{
    //Start Excel and get Application object.
    oXL = new Excel.Application();
    oXL.Visible = false;

    //Get a new workbook.
    oWB = (Excel._Workbook)(oXL.Workbooks.Add(Missing.Value));
    oSheet = (Excel._Worksheet)oWB.ActiveSheet;

    // *****
    oSheet.Cells[2, 6] = "Ship To:";
    oSheet.get_Range("F2", "F2").Font.Bold = true;

    oSheet.Cells[2, 7] = sShipToName;
    oSheet.Cells[3, 7] = sAddress;
    oSheet.Cells[4, 7] = sCityStateZip;
    oSheet.Cells[5, 7] = sContactName;
    oSheet.Cells[6, 7] = sContactPhone;

    oSheet.Cells[9, 1] = "Shipment No:";
    oSheet.get_Range("A9", "A9").Font.Bold = true;
    oSheet.Cells[9, 2] = sJobNumber;

    oSheet.Cells[9, 6] = "Courier:";
    oSheet.get_Range("F9", "F9").Font.Bold = true;
    oSheet.Cells[9, 7] = sCarrierName;

    oSheet.Cells[11, 1] = "Requested Delivery Date:";
    oSheet.get_Range("A11", "A11").Font.Bold = true;
    oSheet.Cells[11, 2] = sRequestDeliveryDate;

    oSheet.Cells[11, 6] = "Courier Acct No:";
    oSheet.get_Range("F11", "F11").Font.Bold = true;
    oSheet.Cells[11, 7] = sCarrierAcctNum;
    // *****

    Method #1
    //oWB.SaveCopyAs(@"C:\Temp\" + sJobNumber +".xls");

    Method #2
    oXL.SaveWorkspace(sJobNumber + ".xls");
}
catch (Exception theException)
{
    String errorMessage;
    errorMessage = "Error: ";
    errorMessage = String.Concat(errorMessage, theException.Message);
    errorMessage = String.Concat(errorMessage, " Line: ");
    errorMessage = String.Concat(errorMessage, theException.Source);
}

1
Kris,请阅读http://stackoverflow.com/faq上的常见问题解答。这不是标签的工作方式。 - John Saunders
1
感谢您提供这个宝贵的信息。 - Kris
4个回答

3

您可以使用SaveFileDialog并让用户选择位置,然后在调用oWB.SaveCopyAs(userselectedlocation)时使用该位置。


3

这只适用于Windows表单吗?我正在尝试从Web应用程序中获取“另存为”对话框。 - Kris
@Kris:你的帖子中没有提到它是一个Web应用程序;我认为你应该添加Web应用程序标签,例如asp.net。 - KMån
@KMan:抱歉,我忘记了那个部分。 :) - Kris

1

-2
你可以试试这个。我尝试过,对我有效。
oWB.SaveAs(@"C:\Temp\" + "test" + ".xlsx");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接