Click here to Skip to main content
15,919,613 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
I have a project where I am using form1 having gridview and form2 containing textboxes. My code runs fine and saves the file to the directory that I choose. The problem is when I try to open the excel file I receive an error from Excel stating “Excel cannot open the file Invoice System.xlsx 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

What I have tried:

form1:
using (var fs = new FileStream("Invoice System.xlsx", FileMode.Create, FileAccess.Write)) { wb.Write(fs); }
form2:
private void button1_Click(object sender, EventArgs e) { string[] rowData = new string[] { textBox1.Text, textBox2.Text}; form1.dataGridView1.Rows.Add(rowData); }
Posted
Updated 11-Jun-18 9:42am
Comments
F-ES Sitecore 11-Jun-18 6:48am    
google "c# create xlsx file" for ways to create a file Excel can understand, you can't just create an empty file the way you are.

C#
using (var fs = new FileStream("Invoice System.xlsx", FileMode.Create, FileAccess.Write)) { wb.Write(fs); } 


This won't write data in proper format into Excel file.

You need to use one of below:
1. OpenXml[^]: Open XML Create Excel from scratch | Wriju's BLOG[^]
2. Excel.Interop[^]: Workbooks.Add method (Microsoft.Office.Interop.Excel)[^]
3. EPPlus[^]: How To Create An Excel File (Development) Using EPPlus .NET Library (C#) - Part One
 
Share this answer
 
Quote:
The problem is when I try to open the excel file I receive an error from Excel stating “Excel cannot open the file Invoice System.xlsx 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

Excel tells you that your file is not a proper Excel data file.
Simply naming a file "Invoice System.xlsx", is not enough to make it an Excel data file or a file that Excel can read.
Excel can read numerous data files: csv, xml, html and more. you have to study what can be done with each and choose witch one fit your needs.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900