How to Create/Open Excel files using OpenXml with C# - c#

I have a console application in which we are creating xlsx files using OPENXML, we are able to create xlsx file & save it into specific folder in application.
But Now we want to show that file as a Save/Open dialog pop up. Then we can able to specify a particular path to save/ to open the existing files.
I am new to this OpenXml, Can anyone please help me on this to proceed further? How can I acheive this? Do we have any built-in DLL for this?
Thanks.

se the Save file dialog. It will prompts the user to select a location for saving a file. After that you can use saveFileDialog.FileName.ToString() property to get the full path.
See the sample code below:
//Save a file in a particular format as specified in the saveAsType parameter
private void OpenSaveFileDialog(int saveAsType)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.InitialDirectory = Convert.ToString(Environment.SpecialFolder.MyDocuments);
saveFileDialog.Filter = "CSV|*.csv|Excel|*.xlsx";
saveFileDialog.FilterIndex = saveAsType;
saveFileDialog.Title = "Save Data";
saveFileDialog.FileName = "My File";
saveFileDialog.ShowDialog();
if (saveFileDialog.FileName != "")
{
//File Path = m_fileName
m_fileName = saveFileDialog.FileName.ToString();
//FilterIndex property is one-based.
switch (saveFileDialog.FilterIndex)
{
case 1:
m_fileType = 1;
break;
case 2:
m_fileType = 2;
break;
}
}
}
Ref:http://msdn.microsoft.com/en-us//library/system.windows.forms.savefiledialog.aspx

Related

A Better way to rename XAML file class when renaming the file?

EDIT: The main issue when renaming the file is to rename xaml contents
My intuition is screaming that there is a better way to do this, but the following works, my question is to see if there a better or an already existing method that can do this
I have a small WPF app that loads xaml files and can be imported/edited and exported.
When the WPF app initialises it makes a placeholder xaml file that you can edit,
"StartingXamlFile.xaml" when exporting I used a SaveFileDialog and the user can change the name. But the contents of the XAML file is not changed according to the file name. Also when importing an existing XAMLfile then editing and exporting(changing name when exporting) the same thing occurs.
Solution:
I set up a Singleton object to hold the file name XamlFile with property content and path. Now the default is set to "StartingXamlFile" when importing this is replaced. This is done following Gang of four Singleton technique
SaveFile code that doesnt work:
SaveFileDialog dlg = new SaveFileDialog();
dlg.FileName = "StartingXamlFile"; // Default file name
dlg.DefaultExt = ".xaml"; // Default file extension
dlg.Filter = "xaml files (*.xaml)|*.xaml|All files (*.*)|*.*"; // Filter files by extension
// Show save file dialog box
var result = dlg.ShowDialog();
if (result == true)
{
File.WriteAllText(dlg.FileName, editedContent);
}
Save File code that does work using Replace:
if (result == true)
{
var name = Path.GetFileNameWithoutExtension(dlg.FileName);
var testing = XamlFile.Content.Replace(XamlFile.Path,name);
File.WriteAllText(dlg.FileName, testing);
}
Just to give this question an accepted answer, I have not found a better way to this other than:
SaveFileDialog dlg = new SaveFileDialog();
dlg.FileName = "StartingXamlFile"; // Default file name
dlg.DefaultExt = ".xaml"; // Default file extension
dlg.Filter = "xaml files (*.xaml)|*.xaml|All files (*.*)|*.*";
// Show save file dialog box
var result = dlg.ShowDialog();
if (result == true)
{
//X:Class replacement is done here
var name = Path.GetFileNameWithoutExtension(dlg.FileName);
var testing = XamlFile.Content.Replace(XamlFile.Path,name);
File.WriteAllText(dlg.FileName, testing);
}
XamlFile is a singleton object that contains the content of the xaml
and initial name of file when starting up or importing, so when you export it
replaces all references to the initial name

How to create a blank excel file using C# forms?

I can't seem to create a new blank excel file so I can write in it with excel Interop later
System.IO.FileStream fs =(System.IO.FileStream)saveFileDialog1.OpenFile();
switch (saveFileDialog1.FilterIndex)
{
case 1:
//write blank xlsx?
break;
case 2:
//write blank xls?
break;
}
fs.Close();
ExportDataSetToExcel(_destinationDataSet, saveFileDialog1.FileName);
If I pass an empty file I got this error
Cant open file because the file format or file extension is not valid.
Verify that the file has not been corrupted and that the file
extension matches the format of the file.
So.. How can I create an empty xls or xls file?
Simplest way
var app = new Microsoft.Office.Interop.Excel.Application();
var wb = app.Workbooks.Add();
wb.SaveAs("File Path.xlsx");
wb.Close();
Empty Excel files are not simple empty files, since they also store some header data. One modern way of writing Excel files is to use Open XML SDK 2.5 as indicated here:
var spreadsheetDocument = SpreadsheetDocument.Create(filepath, SpreadsheetDocumentType.Workbook);
By doing so, you get a reference that allows you to write data to the Excel file.
In order to get a value for filepath, you can you use SaveFileDialog to indicate path to be used like indicated in the documentation:
var saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Excel files|*.xlsx";
saveFileDialog1.Title = "Save an Image File";
saveFileDialog1.ShowDialog();
if(saveFileDialog1.FileName != "")
{
// file name is available here
}
You can make your Excel manipulation in C# even easier by using a third party library such as EPPlus.
Disclaimer: Above hints work only for the Excel 2007 and above formats.
I ended up doing this...
if (saveFileDialog1.FileName != "")
{
var app = new Application();
var wb = app.Workbooks.Add();
switch (saveFileDialog1.FilterIndex)
{
case 1:
wb.SaveAs(saveFileDialog1.FileName);
break;
case 2:
wb.SaveAs(saveFileDialog1.FileName, XlFileFormat.xlExcel8);
break;
}
wb.Close();
app.Quit();
ExportDataSetToExcel(_destinationDataSet, saveFileDialog1.FileName);
}

Bypassing save dialog box in WPF application

I am trying to bypass the save dialog box when using the SaveFileDialog class. I want to be able to write to a document without having to prompt a user to decide if they want to save or not, the file should automatically save when they click a button.
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ;
saveFileDialog1.RestoreDirectory = true ;
saveFileDialog1.InitialDirectory = #"C:\";
if(saveFileDialog1.ShowDialog() == DialogResult.OK)
{
// Code to write the stream goes here.
}
I have tried removing the if statement as well as using...
saveFileDialog1.CreatePRompt = false;
Nothing seems to work... Any ideas?
I think you want to bypass the overwrite prompt dialog.
In this case you can use
saveFileDialog1.OverwritePrompt = false;
Otherwise, you don't need a SaveFileDialog and you can save your stream without using it.
I found my answer. The question I asked was actually two it seems. The first was how to bypass SaveFileDialog, I wanted to use saveFileDialog because it can remember the last folder it accessed and opens to that folder when performing a read/save. That being said I implemented this...
Directory = System.AppDomain.CurrentDomain.BaseDirectory;
This will set Directory to the location of my executable.
Next I got rid of SaveFileDialog and just wrote to a file without ever prompting the user.
Thanks for all the pointers and ideas!
The end result ended up...
Directory = System.AppDomain.CurrentDomain.BaseDirectory;
using(System.IO.StreamWriter file = new System.IO.StreamWriter(Directory, false))
{
// File contents
}
Works perfectly for what I need it for.
If you want to save but you need the user to pick a filename, I would use this:
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
//setup properties of Dialog
bool filenamepicked = false;
while (!filenamepicked)
{
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
//Save file
filenamepicked = true;
}
else
{
MessageBox.Show("You have to use a file name.");
}
}

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

How to know which file is selected in open dialog in c#

I have to open a file dialog. In that I have to choose one file either an XML or MAP file. If the choosen file is MAP file then I have to do step-A or if the choosen file is XML then I have to do step-B. My question is how to know which file is selected from the dialog box application?
OpenFileDialog fileDialog1 = new OpenFileDialog();
fileDialog1.Filter = "XML Files|*.xml|MAP Files|*.map";
fileDialog1.ShowDialog();
How to know which file is selected from the above filter ?
You can use:
string fileName = OpenFileDialog.Filename;
if(fileName.EndsWith(".xml"))
{
//
}
else if(fileName.EndsWith(".map"))
{
//
}
I think you can't do that while it is open.
When user presses OK then pass OpenFileDialog.Filename in Path.GetExtension method or OpenFileDialog.Filename.Endswith(".xml").
Check if extension is XML then do x step otherwise y step.
EDIT
See for functionality that you require, there has to be an event in open file dialog.
There are 2 OpenFileDialog Class
System.Windows.Forms
Microsoft.Win32
Both have only one event OpenFileDialog.FileOK which you can look for.
openFileDialog1.FileName = "";
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string filename = openFileDialog1.FileName;
if (File.Exists(filename))
{
//do something here
}
}
The FileName attribute of OpenFileDialog is the file name selected.
You could even use similar extensions in a switch with stacked labels and use the default case for unsupported file types:
switch (extension)
{
case "xml":
case "xaml":
Debug.WriteLine("It's an XML!");
break;
case "map":
Debug.WriteLine("It's a map!");
break;
default:
MessageBox.Show("Please select an XML or MAP file");
// Show the dialog again
break;
}
Well, the above answers will work if luckily all the filters have different extensions. but if we are talking about different File versions with the same extension then we can get the selected filter through this code:
SaveFileDialog dlg = new SaveFileDialog();
dlg.Filter = "Excel 97|*.xls|Excel 95|*.xls";
if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
//Filer index is 1 based.
switch (dlg.FilterIndex)
{
case 1:
//Filter name: Excel 97
break;
case 2:
//Filter name: Excel 95
break;
}
}

Categories

Resources