saving data from c# to Excel crashes - c#

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

Related

How to read data from Excel which is open and getting updated every seconds using C# ASP.NET?

I am using Office.Interop.Excel to read data from Excel using C# ASP.Net & Dotnet 6.
I can read the Data and everything seems to be working fine.
But I have a challenge here.
The excel which I am reading data from would be updated every second.
But I am seeing an error while trying to open it and update random data.
The error says that the file is locked for editing.
Please have a look at the code below:
public double GetGoldPrice()
{
string filename = #"D:\Test.xlsx";
int row = 1;
int column = 1;
Application excelApplication = new Application();
Workbook excelWorkBook = excelApplication.Workbooks.Open(filename);
string workbookName = excelWorkBook.Name;
int worksheetcount = excelWorkBook.Worksheets.Count;
if (worksheetcount > 0)
{
Worksheet worksheet = (Worksheet)excelWorkBook.Worksheets[1];
string firstworksheetname = worksheet.Name;
var data = ((Microsoft.Office.Interop.Excel.Range) worksheet.Cells[row, column]).Value;
excelApplication.Quit();
return data;
}
else
{
Console.WriteLine("No worksheets available");
excelApplication.Quit();
return 0;
}
}
My end goal is to get live data from Excel whenever I fire the function.
The Excel would be open and can be editing any time.
Please help!
You said your file is xlsx so you would be better not using Interop but Open XML SDK 2.5. Then you can open the file in read only mode:
using (SpreadsheetDocument spreadsheetDocument =
SpreadsheetDocument.Open(fileName, false))
{
// Code removed here.
}
Check here to get familiar with Open XML SDK

C# cannot read from read-only Excel file

I have a folder on my PC containing multiple Excel spreadsheets that are all marked as read-only.
The folder is synced to my company's Sharepoint via OneDrive.
When I try to programmatically read data from one of these sheets via Microsoft.Office.Interop.Excel, I keep getting the You cannot use this command on a protected sheet error.
Here's the code I use to open the file:
public ExcelReader(String filePath)
{
this.filePath = filePath;
FileName = filePath.Substring(filePath.LastIndexOf("\\")+1);
app = new Excel.Application();
app.DisplayAlerts = false;
workbook = app.Workbooks.Open(filePath, false, true); //open in read only
}
public void openSheet(String sheet)
{
SheetName = sheet;
worksheet = workbook.Sheets[sheet];
Excel.Range last = worksheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
ColumnsTotal = last.Column;
RowsTotal = last.Row;
}
The line that throws the exception is Excel.Range last = worksheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);.
I figured that since I explicitly tell the Workbook to open in Read-only mode, and since I never modify the content of these files, the fact that files are read-only shouldn't be a problem.
What am I doing wrong here? How do I read the content of these files without unprotecting them (I can't do that for security reasons)?

Removing entire excel row by searching for specific words using C#

I am new to C# and have been trying to make my very own little tool to help me at work.
For the most part I've got everything i needed done but I need to do one more thing to have the entire program work as i want it too.
I need to go through my excel file, search for a specific word, (or other criteria) and when that specific word is found, the entire row on which it was found to be deleted.
So far i haven't had much luck in finding the proper code to help me succed in this.
Any help or suggestions would be of most help and would be very appreciated.
Thank you in advance.
Here is a part of my code:
This part is used to activate my macro:
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
excel.Visible = true;
//3
Workbook wb1 = excel.Workbooks.Open(#"C:\Users\amohan\AppData\Local\Temp\amohan.xls");
Workbook wb2 = excel.Workbooks.Open(#"C:\Users\amohan\Desktop\Saw pt. Test\Saw.xlsm");
//4
Microsoft.Office.Interop.Excel.Range source = wb1.Sheets["amohan"].Range("A1:X10000");
Microsoft.Office.Interop.Excel.Range destination = wb2.Sheets["bom"].Range("A1:X10000");
//5
source.Copy(destination);
wb2.Activate();
excel.Run("Macro2");
//6
wb1.Close();
wb2.SaveAs(#"C:\Users\amohan\Desktop\Saw pt. Test\I.O. (date&time)\Formatare - "
+ DateTime.Now.ToString("dd.MM.yyyy - ") + DateTime.Now.ToString("hh.mm.ss") + ".xlsm");
excel.DisplayAlerts = false;
wb2.SaveAs(#"C:\Users\amohan\Desktop\Saw pt. Test\Replaceable Excel File.xlsm");
wb2.Close();
excel.Quit();
GC.Collect();
and this part is for copying it to further paste the info (final step)
Microsoft.Office.Interop.Excel.Application sourceApp;
Microsoft.Office.Interop.Excel.Workbook sourceWorkBook;
Microsoft.Office.Interop.Excel.Worksheet sourceWorkSheet;
Microsoft.Office.Interop.Excel.Range sourceRange;
string sourcePath;
sourcePath = (#"C:\Users\amohan\Desktop\Saw pt. Test\Replaceable Excel File.xlsm");
sourceApp = new Microsoft.Office.Interop.Excel.Application();
sourceWorkBook = sourceApp.Workbooks.Open(sourcePath);
sourceWorkSheet = sourceWorkBook.Worksheets.get_Item(3);
sourceRange = sourceWorkSheet.UsedRange;
sourceRange.Copy(Type.Missing);
excel.Quit();
GC.Collect();
I just need to eliminate some info before copying it to my clipboard.

How to fix file format and extension don't match?

I created a code in c# which creates and saves excel file. The code can successfully create and save excel file, but when I open the excel file created, it displays a warning message telling:
The file format and extension of 'filename.xls' don't match. The file could be corrupted or unsafe. Unless you trust its source, don't open it. Do you want to open it anyway?
I am using the following code:
private void button1_Click(object sender, EventArgs e)
{
saveFileDialogSummary.Filter = "Excel Flie|*.xls";
saveFileDialogSummary.FilterIndex = 0;
saveFileDialogSummary.RestoreDirectory = true;
saveFileDialogSummary.CreatePrompt = true;
saveFileDialogSummary.Title = "Export Excel File To";
Excel.Application ExcelApp = new Excel.Application();
ExcelApp.Application.Workbooks.Add(Type.Missing);
ExcelApp.Columns.ColumnWidth = 30;
for (int i = 0; i < dataGridViewSummary.Rows.Count; i++)
{
DataGridViewRow row = dataGridViewSummary.Rows[i];
for (int j = 0; j < row.Cells.Count; j++)
{
ExcelApp.Cells[i + 1, j + 1] = row.Cells[j].ToString();
}
}
DialogResult res = saveFileDialogSummary.ShowDialog();
if(res == DialogResult.OK){
ExcelApp.ActiveWorkbook.SaveCopyAs(saveFileDialogSummary.FileName);
ExcelApp.ActiveWorkbook.Saved = true;
ExcelApp.Quit();
}
}
What should I do to avoid receiving that warning message?
I know this problem may be resolved by now, but just trying to help you without modifying the code can still use .xls format in your's and suppress this warning while opening the file by setting a registry.
Open reg edit, navigate to HKEY_CURRENT_USER\Software\Microsoft\Office\14\Excel\Security
Create a DWord with name ExtensionHardening and set the value to 0.
This might get your system vulnerable, but it is not a big deal when working in organisation network, at-least when you're sure of downloading the type of doc and source.
Just change the .xls to .xlsx if you have the latest office installed.
The file extension .xls and .xlsx file contain different-different layout. the extension .xls use in version 2003 whereas then version .xlsx extension to be used.
You must export excel file to .xlsx format. It will support in all version as i used.
Add below DLLS into bin folder
1. ClosedXML.dll
2. DocumentFormat.OpenXml.dll
Code to Export to .xlsx
DataTable dt = new DataTable();
//Create column and inser rows
using (XLWorkbook wb = new XLWorkbook())
{
var ws = wb.Worksheets.Add(dt, Sheetname);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.Charset = "";
HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + p_FileName + ".xlsx");
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(HttpContext.Current.Response.OutputStream);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
}
The solution for "file format and extension don't match" is to close the work book**($workbook->close;)** at last after all necessary writings done on to the file.
I faced the same issue while opening the "XLS" file from mail. I created a file and inserted all my stuff init and without closing the workbook I send the mail as an attachment. Later I realized that have to close the workbook and send as an attachment.

Save excel file using savefiledialog class in C#

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!

Categories