Export Crystal Report To Excel - Specify Directory - c#

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.

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);

Related

C#: Saving iText7 PDFs into a folder chosen by the user with a dialog

I would make a simple program in C# with Windows forms, which gets some data given by the user thanks to some textboxes, and when He presses a button, a dialog (I don't know which one) is displayed, in order to explore the pc folders and choose a destination for saving it there.
Well, I used a FolderBrowserDialog (I don't know if that's the right one for the purpose), but there's a problem: in order to store a PDF with itext7, I have to give an Environment.SpecialFolder variable, while the method selectedPath() to get the user path of the formBrowserDialog returns a string.
I tried to convert the string into Environment.SpecialFolder in some way, but I always get a System.ArgumentException
Here's my code:
string name = txtName.Text;
//
//bla bla bla getting the parameters given by the user
//...
string pdfName = surname+ " - " + hours + "ː" + minutes + ".pdf";
string folder="";
//"fbd" is the FolderBrowserDialog
if (fbd.ShowDialog() == DialogResult.OK)
{
//here I get the folder path (I hope I've chosen the right dialog for this scope, which is a FolderBrowserDialog)
folder = fbd.SelectedPath;
//starting my pdf generation
//here is my attempt to write something in order to parse the path string into an Environment.SpecialFolder type, to use it as a parameter in getFolderPath()
Environment.SpecialFolder path = (Environment.SpecialFolder)Enum.Parse(typeof(Environment.SpecialFolder), folder);
//here it's supposed to give to the GetFolderPath method the Environment.SpecialFolder type.
var exportFolder = Environment.GetFolderPath(path); //ON THIS LINE I GET THE EXCEPTION
var exportFile = System.IO.Path.Combine(exportFolder, pdfName);
using (var writer = new PdfWriter(exportFile))
{
using (var pdf = new PdfDocument(writer))
{
var doc = new Document(pdf);
doc.Add(new Paragraph("
//bla bla bla writing my things on it
"));
}
}
//pdf creation ends
}
To simplify all of this, you don't need to Environment.SpecialFolder variable at all, nor do you need to pass it as a parameter.
The reason that an exception was thrown is because you tried to parse a string into an Environment.SpecialFolder variable enum, when the string could not be parsed into one.
You can look here to see the list of enums included. I would wager that the specific path you selected matches none of those.
Here's what your code is currently doing:
Selecting a path
Trying to parse that path to get an enum for a
special folder
Trying to get the string associated with that
Environment.SpecialFolder variable (so if you had actually been
able to parse it, you would've ended up with just what you started
with)
Combining that string with the name you wanted to give the PDF.
You can simplify all of this by omitting steps 2 and 3, which cause the error.
string pdfName = surname+ " - " + hours + "ː" + minutes + ".pdf";
//You select the folder here
if (fbd.ShowDialog() == DialogResult.OK)
{
string folder = fbd.SelectedPath;
//combine the path of the folder with the pdf name
string exportFile = System.IO.Path.Combine(folder, pdfName);
using (var writer = new PdfWriter(exportFile))
{
using (var pdf = new PdfDocument(writer))
{
var doc = new Document(pdf);
doc.Add(new Paragraph("//bla bla bla writing my things on it"));
}
}
//Pdf creation ends
}

Getting the path of a file from the SaveFileDialog to a string

In my form I have a button that launches the SaveFileDialog module. Then when I load a file, I want to save the path as a string and put that text into a text box on the form. I'm not sure how to do this, or even where to start?
Well the problem with your question is that you say when you "load a file", but you cannot load a file from the SaveFileDialog module. However, if you are opening a file via the OpenFileDialog module, then you are able to use this solution to get the directory path of the file you just loaded:
if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
{
var directoryPath = Path.GetDirectoryName(openFileDialog1.FileName);
if(!string.IsNullOrEmpty(directoryPath))
textBox1.Text = directoryPath;
}
Otherwise, if you are wanting to get the file path of whatever file you saved originally, you can use pretty much the same solution to get the directory path:
if (saveFileDialog1.ShowDialog(this) == DialogResult.OK)
{
var directoryPath = Path.GetDirectoryName(saveFileDialog1.FileName);
if (!string.IsNullOrEmpty(directoryPath))
textBox1.Text = directoryPath;
}

Create a “Open” Dialog Button and get the the file name with extension .dat

I want to create a browse (OpenFile Dialog) Button to search my local drive and then write out the selected file name (not the full path ) to a TextBox. It should show Only .dat extension files.
I am using Visual Studio 2008
Any help much appreciated!
Next time you ask anything, show some examples of what you have tried please.
private string GetDatFileName()
{
// Create Open File Dialog with the correct filter
using (OpenFileDialog ofd = new OpenFileDialog()) {
ofd.Filter = "dat-file (*.dat) | *.dat";
string fileNameAndFolder = "";
string fileName = "";
// Get file plus folder.
if (ofd.ShowDialog() == DialogResult.OK)
{
fileNameAndFolder = ofd.FileName;
// Split folder and filename
fileName = Path.GetFileName(fileNameAndFolder);
}
// Return the fileName;
return fileName;
}
}
What I have done here is create an OpenFileDialog and set its filter to the required "dat"-format. Only .dat-files will show up in the browserdialog.
Next, you show the dialog and check if the result is OK. If the result is, you will get the full filename (with folder) into a variable. All thats left then, is to get the filename from fileNameAndFolder.

Creating and saving files in C#

I need to create and write to a .dat file. I'm guessing that this is pretty much the same process as writing to a .txt file, but just using a different extension.
In plain english I would like to know how to:
-Create a .dat file
-Write to it
-And save the file using SaveFileDialog
There are a few pages that I've been looking at, but I think that my best explanation will come from this site because it allows me to state exactly what I need to learn.
The following code is what I have at the moment. Basically it opens a SaveFileDialog window with a blank File: section. Mapping to a folder and pressing save does not save anything because there is no file being used. Please help me use this to save files to different locations.
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
dlg.FileName = "";
dlg.DefaultExt = "";
Nullable<bool> result = dlg.ShowDialog();
if (result == true)
{
string filename = dlg.FileName;
}
Pages that I've been looking at:
-http://msdn.microsoft.com/en-us/library/8bh11f1k.aspx
-http://social.msdn.microsoft.com/Forums/en-US/cd0b129f-adf1-4c4f-9096-f0662772c821/how-to-use-savefiledialog-for-save-text-file
-http://msdn.microsoft.com/en-us/library/system.io.file.createtext(v=vs.110).aspx
Note that the SaveFileDialog only yields a filename but does not actually save anything.
var sfd = new SaveFileDialog {
Filter = "Text Files (*.txt)|*.txt|All files (*.*)|*.*",
// Set other options depending on your needs ...
};
if (sfd.ShowDialog() == true) { // Returns a bool?, therefore the == to convert it into bool.
string filename = sfd.FileName;
// Save the file ...
}
Use the filename you are getting from the SaveFileDialog and do the following:
File.WriteAllText(filename, contents);
That's all if you intend to write text to the file.
You can also use:
File.WriteAllLines(filename, contentsAsStringArray);
using(StreamWriter writer = new StreamWriter(filename , true))
{
writer.WriteLine("whatever your text is");
}

Save a browsed file to a pre-defined folder using c#

I am working on a WinForm Application using c#. I am using a button to browse for an image file (.jpeg or .bmp). When the user browses the file and clicks ok, on the click of another "Proceed or Update" button, I want that the browsed file should be renamed and saved to a predefined directory where all image files will be saved by default, without much user interaction!
How can I achieve this? I have used openFileDialog for browsing the file, but dont know what else to do.
//detination filename
string newFileName = #"C:\NewImages\NewFileName.jpg";
// if the user presses OK instead of Cancel
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
//get the selected filename
string filename = openFileDialog1.FileName;
//copy the file to the new filename location and overwrite if it already exists
//(set last parameter to false if you don't want to overwrite)
System.IO.File.Copy(filename, newFileName, true);
}
More information on the Copy method.
First you have to implement a copy function that can make unique file names:
private void CopyWithUniqueName(string source,
string targetPath,
string targetFileName)
{
string fileName = Path.GetFileNameWithoutExtension(targetFileName);
string extension = Path.GetExtension(targetFileName);
string target = File.Exists(Path.Combine(targetPath, targetFileName);
for (int i=1; File.Exists(target); ++i)
{
target = Path.Combine(targetPath, String.Format("{0} ({1}){2}",
targetFileName, i, extension));
}
File.Copy(source, target);
}
Then you can use it, suppose defaultTargetPath is the default target file where to copy images and defaultFileName is the default file name for images:
void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() != DialogResult.OK)
return;
CopyWithUniqueName(openFileDialog1.FileName,
defaultTargetPath, defaultFileName);
}
In case of multiple selection:
foreach (string fileName in openFileDialog1.FileNames)
{
CopyWithUniqueName(fileName,
defaultTargetPath, defaultFileName);
}
You'll get this (suppose defaultFileName is "Image.png"):
Source Target
A.png Image.png
B.png Image (1).png
C.png Image (2).png
You can do that with the File.Copy()-method. Just put the predefined directory and the new filename as the destination parameter.
For more info see here

Categories

Resources