簡體   English   中英

創建和保存 Excel 文件

[英]Creating and Saving an Excel File

我有以下代碼在后面的 C# 代碼中創建一個新的 Excel 文件。 當我嘗試保存文件時,我希望用戶選擇保存位置。

在方法 #1 中,我可以使用工作簿 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);
}

您可以使用 savefiledialog 並讓用戶選擇他們的位置,然后您可以在調用 oWB.SaveCopyAs(userselectedlocation) 時使用該位置

使用 SaveFileDialog 類從用戶那里獲取所需的路徑:

http://msdn.microsoft.com/en-us/library/system.windows.forms.savefiledialog.aspx

你為什么不使用SaveFileDialog 請參閱如何:使用 SaveFileDialog 組件保存文件

- 編輯 -

如果是 asp.net 應用程序,則此討論可能有助於生成保存文件對話框。

您可以嘗試ZetExcel獲得出色的結果。 去嘗試一下。

你可以試試這個。 我試過了,它對我有用

oWB.SaveAs(@"C:\Temp\" + "test" + ".xlsx");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM