I need to create and save a Excel file without inform in the code the path and file name. So I can use the savefiledialog to show the save box to input the path and file name, but I can´t use it correctly.
I tried to use the worksheet.saveas but this class doesn´t show the save box to input the path and file name.
How can I save a excel file with that save box?
The basic mechanic of it is this:
public void SaveExcelWorkBook()
{
OpenFileDialog openDlg = new OpenFileDialog();
openDlg.InitialDirectory = #"C:\";
openDlg.ShowDialog();
string path = openDlg.FileName;
if (openDlg.ShowDialog() == DialogResult.OK)
{
try
{
Application excelApp = new Application();
Workbook workBook = excelApp.Workbooks.Open(path);
Worksheet workSheet = (Worksheet)workBook.Worksheets[1];
// Do your work here inbetween the declaration of your workbook/worksheet
// and the save action below.
workBook.SaveAs(/*path to save it to*/); // NOTE: You can use 'Save()' or 'SaveAs()'
workBook.Close();
}
catch (Exception ex)
{
}
}
}
I think I should also mention that Interop objects are unmanaged so, you will want to make sure that you are releasing them after calling .Close(). Here is an example:
Marshal.ReleaseComObject(workBook);
There are two fantastic tutorials for using Excel here and here. Good luck!
Related
I work on a project where I'd like to save some data in an Excel sheet,
Here is my code:
private void myButton11_Click(object sender, EventArgs e)
{
Microsoft.Office.Interop.Excel.Application excel;
Microsoft.Office.Interop.Excel.Workbook excelworkbook;
Microsoft.Office.Interop.Excel.Worksheet excelsheet;
excel = new Microsoft.Office.Interop.Excel.Application();
excel.Visible = false;
excel.DisplayAlerts = false;
excelworkbook = excel.Workbooks.Add(Type.Missing);
excelsheet = (Microsoft.Office.Interop.Excel.Worksheet)excelworkbook.ActiveSheet;
excelsheet.Name = "dataToExcel";
// fill in data
excelsheet.Cells[1, 1] = "test";
excelsheet.Cells[3, 3] = "test2";
// save excel
excelworkbook.SaveAs(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "//dataToExcel.xls",
Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal);
true, true, 1, 10, false);
}
The problem is when executing it crashes and shows me this error message:
System.Runtime.InteropServices.COMException
HResult=0x800A03EC
Message=Coudn't access file. Please try thoses options :
• Make sure the file exist.
• Make sure the file is not in read only.
• Make sure file path isn't containing thoses characteres: < > ? [ ] : | or *
• Make sure the file path and names do not take more than 218 caracteres.
C:\Users\corentin.boudaud\source\repos\FabLoop_project_V0.0.0\FabLoop_project_V0.0.0\Program.cs :ligne 20
The crash occurs on "SaveAs", the file I'm writing to is in my documents (public, write available)
Any idea where the problem might come from?
Thanks
You can save it easy as a .csv file. CSV is also a tabel and if you open it it will open in excel.
You can do this with System.IO
Thats a csv file in excel:
and thats a csv file in notepad++
I found the problem,
when using excelworkbook.SaveAs(), the path need to be using '\' to set the path and not '/'
I can then save the file as I want, .csv .xls or .xlsx
Is there any way to check if a specific word document is Open? When I open document myself before opening the app when I tell to my app to write something in document first try to open the document and thats where my app is stuck.Is there a way to check before I try to open if the file is already opened? at this moment my code looks like this:
object filename = s; // s is a string path which I get from database
Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
Microsoft.Office.Interop.Word.Document doc1 = app.Documents.Open(s);
object missing = System.Reflection.Missing.Value;
app.Visible = true;
just put your code in a
try
{
//your code here
}
catch (Exception e)
{
//your behavior when the file is opened
}
I am a newbie and i want to generate PDF from Infragistics, Xamdatagrid. However as Infragistics doesnt provide this functionality ,i have generated XPS of Xamdatagrid and wants to convert that to XPS programitically. What are the possible work around and third party tool to do that?
If you export the xamDataGrid in an excel file then is pretty simple to use Excel.Interop and ask excel to export its workbook in PDF format
// Export an excel workbok in PDF format with landscape orientation
private static void ExportWorkbookToPDF(string workbook, string output)
{
Microsoft.Office.Interop.Excel.Application excelApplication =
new Microsoft.Office.Interop.Excel.Application();
excelApplication.ScreenUpdating = false;
excelApplication.DisplayAlerts = false;
excelApplication.Visible = false;
Microsoft.Office.Interop.Excel.Workbook excelWorkbook =
excelApplication.Workbooks.Open(workbook);
if (excelWorkbook == null)
{
excelApplication.Quit();
excelApplication = null;
excelWorkbook = null;
throw new NullReferenceException("Cannot create new excel workbook.");
}
try
{
((Microsoft.Office.Interop.Excel._Worksheet)excelWorkbook.ActiveSheet).PageSetup.Orientation =
Microsoft.Office.Interop.Excel.XlPageOrientation.xlLandscape;
excelWorkbook.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF, output);
}
finally
{
excelWorkbook.Close();
excelApplication.Quit();
excelApplication = null;
excelWorkbook = null;
}
}
if you wish to create only pdf. then the simplest thing have any pdf printer on machine. One like PDF Creater and then just call the printing thing like below on the XamDataGrid.
make sure you select the PDF Printer on the Printer Selection Dialog Box.
// 1. Create Report object
Report reportObj = new Report();
// 2. Create EmbeddedVisualReportSection section.
// Put the grid you want to print as a parameter of section's constructor
EmbeddedVisualReportSection section = new EmbeddedVisualReportSection(xamdg);
// 3. Add created section to report's section collection
reportObj.Sections.Add(section);
// Optional. If you have progress indicator set its Report property to created report
// progressInfo.Report = reportObj;
// 4. Call print method
reportObj.Print(true, false);
You can also use thirdparty software like GhostXPS.
http://www.ghostscript.com/download/gxpsdnld.html
Just start the convert process with the correct arguments and it will generate the PDF for you. The drawback is that you have to save the files temporary to the disk and check the return code. Also make sure you are not violating the GNU license
I have DataTable object. How can I export it into an XLS file?
I tried to render it via DataGrid
DataGrid dgGrid = new DataGrid();
dgGrid.DataSource = dt;
dgGrid.DataBind();
dgGrid.RenderControl(hw);
but the file is very large and the OutOfMemoryException appears.
I can use http://epplus.codeplex.com/.
I need C# function.
There are a number of options, one of them being the Access OLE DB Provider which also operates in terms of DataTables.
If you want more fine-grained support over the document, I'd recommend the Open XML SDK 2.0, whixh is .xmlx only.
For raw data, I think that Access OLE DB (also reffered to as the ACE provider) is the best choice since it enables a database-like experience. Open XML assumes fairly good knowledge of XML and the willingnes to experiment a bit more. On the other hand, you can apply formatting, add formulas and other advanced features.
Ok, find a solution here: http://bytesofcode.hubpages.com/hub/Export-DataSet-and-DataTable-to-Excel-2007-in-C
Just download epplus library and call method:
private void GenerateExcel(DataTable dataToExcel, string excelSheetName)
{
string fileName = "ByteOfCode";
string currentDirectorypath = Environment.CurrentDirectory;
string finalFileNameWithPath = string.Empty;
fileName = string.Format("{0}_{1}", fileName, DateTime.Now.ToString("dd-MM-yyyy"));
finalFileNameWithPath = string.Format("{0}\\{1}.xlsx", currentDirectorypath, fileName);
//Delete existing file with same file name.
if (File.Exists(finalFileNameWithPath))
File.Delete(finalFileNameWithPath);
var newFile = new FileInfo(finalFileNameWithPath);
//Step 1 : Create object of ExcelPackage class and pass file path to constructor.
using (var package = new ExcelPackage(newFile))
{
//Step 2 : Add a new worksheet to ExcelPackage object and give a suitable name
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(excelSheetName);
//Step 3 : Start loading datatable form A1 cell of worksheet.
worksheet.Cells["A1"].LoadFromDataTable(dataToExcel, true, TableStyles.None);
//Step 4 : (Optional) Set the file properties like title, author and subject
package.Workbook.Properties.Title = #"This code is part of tutorials available at http://bytesofcode.hubpages.com";
package.Workbook.Properties.Author = "Bytes Of Code";
package.Workbook.Properties.Subject = #"Register here for more http://hubpages.com/_bytes/user/new/";
//Step 5 : Save all changes to ExcelPackage object which will create Excel 2007 file.
package.Save();
MessageBox.Show(string.Format("File name '{0}' generated successfully.", fileName)
, "File generated successfully!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
First of all, Google is your best friend. Also you can search on this site.
Some solutions:
You can write an excel file with SQL.
You can use the reference to Microsoft Office library to create an excel file
You can write an XML file.
why does this cause an occurrence of excel to be open?
OpenFileDialog openFileDialog1 = new OpenFileDialog();
DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
if (result == DialogResult.OK) // Test result.
{
//EXCEL.EXE *32 is now showing in the task manager!
i am choosing an XLSX file from the openfiledialog and as shown above i am seeing the process in the task manager.
can someone please tell me how is this possible?
If Excel is already open, you should try to get this instance, instead of creating a new one.
using System.Runtime.InteropServices;
...
Excel.Application xl = null;
try {
// Try to get an existing instance
xl = (Excel.Application)Marshal.GetActiveObject("Excel.Application");
} catch (COMException ex) {
// Excel was not open. Open a new instance
xl = new Excel.ApplicationClass();
}