我有以下代码,可以在后面的 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) 时使用该位置
关于c# - 创建并保存 Excel 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2740137/