问题
I have crystal reports (using C#) that I pull and want to export to Excel. I manage to pull and export the report just fine. But in the code I manually specify the export directory.
Code:
myEquipCalRPT.ExportToDisk(ExportFormatType.Excel, "C:\\Temp\\ReportName.xls");
I know the path must be a string value. How can I ask the user where he/she wants to export the report to (and give it a name) instead of manually specifying the path in the code?
I tried using "SaveFileDialog" with the code below and then I get this exception: "Additional information: The given path's format is not supported.". This allows the user to specify a file name, although I noticed the file type just below the file name box is not set, and have no types to select from either.
SaveFileDialog browser = new SaveFileDialog();
string directoryPath = "";
ienter code here`f (browser.ShowDialog() == DialogResult.OK)
{
directoryPath = browser.ToString(); // prints path
}
myEquipCalRPT.ExportToDisk(ExportFormatType.Excel, directoryPath);
If I use "FolderBrowserDialog", I get the error: "Additional information: Access to the path 'C:\Directory' is denied." which I suspect is due to only giving a directory path, but no file name.
FolderBrowserDialog browser = new FolderBrowserDialog();
string directoryPath = "";
if (browser.ShowDialog() == DialogResult.OK)
{
directoryPath = browser.SelectedPath; // prints path
}
myEquipCalRPT.ExportToDisk(ExportFormatType.Excel, directoryPath);
If I try the following, I get no error, but also no file is saved:
FolderBrowserDialog browser = new FolderBrowserDialog();
string directoryPath = "";
string FileName = "ExcelExport.xls";
string Path = directoryPath + FileName;
if (browser.ShowDialog() == DialogResult.OK)
{
directoryPath = browser.SelectedPath; // prints path
}
myEquipCalRPT.ExportToDisk(ExportFormatType.Excel, Path);
Also, how can I export to .xlsx instead of .xls? I can specify the extension in the path as .xlsx, but it does not want to open. Need to remove the X at the end to make it work.
回答1:
I ended up with this code to get the path correct as the path was given through as "System.Windows.Forms.SaveFileDialog: Title: , FileName: C:\Temp\test.xls" and not "C:\Temp\test.xls" with all the dialog boxes.
SaveFileDialog browser = new SaveFileDialog();
string directoryPath = "";
if (browser.ShowDialog() == DialogResult.OK)
{
directoryPath = browser.FileName.ToString();
}
And the you can use one of these lines to write the file, depending on which way you chose to use export the report:
myRPT.ExportToDisk(ExportFormatType.Excel, "C:\\Temp\\AMCMaintTempExcelReportFile.xls")
CrDiskFileDestinationOptions.DiskFileName = directoryPath;
myRPT.ExportToDisk(ExportFormatType.Excel, directoryPath);
来源:https://stackoverflow.com/questions/52099119/export-crystal-report-to-excel-specify-directory