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

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.

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

Writing to Excel file when it's opened by another process

I'm wondering if it is possible to write to an Excel file using C#/EPPlus while I have the file open. I continue to get exceptions while trying to write using my program and I can't find anything online.
Here is the code I have to append to an existing worksheet which works fine when the spreadsheet isn't opened
public static void AppendExistingMailingWorkbook(string workSheet, string filePath, IList<MailingReportItem> reportData)
{
//create a fileinfo object of an excel file on the disk
FileInfo file = new FileInfo(filePath);
Object thisLock = new Object();
lock (thisLock)
{
//create a new Excel package from the file
using (ExcelPackage excelPackage = new ExcelPackage(file))
{
ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets[workSheet];
var rowToAppend = worksheet.Dimension.End.Row + 1;
for (int i = 0; i < reportData.Count; i++, rowToAppend++)
{
worksheet.Cells[rowToAppend, 1].Value = reportData[i].BatchDate.Date.ToString("MM/dd/yyyy");
worksheet.Cells[rowToAppend, 2].Value = reportData[i].BatchId;
worksheet.Cells[rowToAppend, 3].Value = reportData[i].FileName;
worksheet.Cells[rowToAppend, 4].Value = reportData[i].PageCount;
worksheet.Cells[rowToAppend, 5].Value = reportData[i].MailDate;
}
//save the changes
excelPackage.Save();
}
}
}
In Excel, set the workbook to be shared. From the office help:
Open workbook in Excel
Click Review > Share Workbook
On the Editing tab, select the Allow changes by more than one user ... check box.
On the Advanced tab, select the options that you want to use for tracking and updating changes, and then click OK.
If this is a new workbook, type a name in the File name box. Or, if this is an existing workbook, click OK to save the workbook.
If the workbook contains links to other workbooks or documents, verify the links and update any links that are broken.
Click File > Save.
When you're done, - Shared will appear at the top of the Excel window, next to the filename.
The file will then be opened non-exclusively, allowing others to edit it while Excel has it open.

mso-data-placement:same-cell not working

I am exporting data into Excel from a web page. This should be a no brainer, but there are <p> tags in the data. This causes Excel to create new rows when the data should all be in the same cell. After some research I found that mso-data-placement should do the trick, but it's not working. Excel opens, the data is displayed, but extra uncessary rows are created. Here is the code I use to export the data:
protected void doexcel()
{
string style = #"<style type='text/css'>P {mso-data-placement:same-cell; font-weight:bold;}</style>";
HttpResponse response = HttpContext.Current.Response;
// first let's clean up the response.object
response.Clear();
response.Charset = "";
//set the response mime type for excel
response.ContentType = "application/vnd.ms-excel";
Random RandomClass = new Random();
int RandomNumber = RandomClass.Next();
String filename = "a" + RandomNumber + DateTime.Now + ".xls";
response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"" );
// create a string writer
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
HttpContext.Current.Response.Write(style);
SqlDataSourceEmployeeAssets.ConnectionString = MyObjects.Application.CurrentContext.ConnectionString;
String sql = (string)Session["sql"];
SqlDataSourceEmployeeAssets.SelectCommand = sql;
// lCount.Text = "Query returned " + getCount(query) + " rows.";
DataGrid dge = new DataGrid();
dge.DataSource = SqlDataSourceEmployeeAssets;
dge.DataBind();
dge.RenderControl(htw);
response.Write(sw.ToString());
response.End();
}
}
}
This is an example of the raw data in the database that is giving me grief:
<P>4/13/2011 : Cheng "Jonathan" Vaing is with BSES Graffiti Unit.</P><P>4/13/2011 : Cheng "Jonathan" Vaing is with</P>
Suggestions?
I tried a couple of other things
I went straight to the data and added the mso-data-placement attribute to the paragraph tag inline. Still didn't work. The data looked like this
<P style="mso-data-placement:same-cell> my data </p>
I tried other mso-* attributes, that didn't work either. For example, I changed my stylesheet to look like this
<style type='text/css'>P {mso-highlight:yellow}</style>";
Why oh why doesn't Excel recognize my mso-* attributes?!?!
There is a solution but it is not clean.
After the dge.DataBind, place the following code. This will encode the text of each cell
foreach (DataGridItem dgi in dge.Items)
{
foreach (TableCell cell in dgi.Cells)
{
cell.Text = WebUtility.HtmlEncode(cell.Text);;
}
}
The Excel file, when opened, should show the raw data with the markup, all in one cell.
I found that this works because Excel actually encodes the text, as well. To see what Excel does in action, do the following:
Create a new workbook in Excel (I am using Office 2013).
In the first cell, paste the raw data (as you have it displayed). Do this by first pressing F2 (insert into cell), then paste the text.
Save the workbook as an HTML file (or web page).
Using windows explorer, go to the folder location of where you saved the file. There should be a hidden folder (i think it is hidden) with the same name as your file. For example, if your workbook is Book1.htm, there should be a folder labeled Book1_files.
In this folder, there should be an HTM file with the name sheet001.htm. Open this file in notepad (or any text editor...not excel or word)
Locate your raw data. You will see that the text is not showing the HTML markup, rather it is showing the encoded version.
Hope this helps.

Convert xls or xlsx file with multiple sheets into one csv file using interop

I am trying to convert a xls or xlsx file with multiple sheets into one CSV file using c# and the interop library. I am only getting the one sheet in the CSV file. I know I can specify the sheet to save as or change the active sheet to save that one but I am looking for a solution to append all the sheets to the same CSV file that will work with both xls and xlsx files. I am automating this and don't care what is in the excel document just want to pull the string values out and append it to the csv file. Here is the code I am using:
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
app.Visible = false;
app.DisplayAlerts = false;
Workbook wkb = app.Workbooks.Open(fullFilePath);
wkb.SaveAs(newFileName, XlFileFormat.xlCSVWindows);
Is this even possible?
I'm just getting started tackling a similar situation, but I believe this may address your needs:
http://www.codeproject.com/Articles/246772/Convert-xlsx-xls-to-csv
This uses the ExcelDataReader api that you can get from NuGet
http://exceldatareader.codeplex.com/
Like Tim was saying, you're going to have to make sure and possibly validate that the columns and structure are the same between sheets. You may also have to eat the header rows on all the sheets after the first one. I'll post an update and some code samples once I've finished.
Update [7/15/2013]. Here's my finished code. Not very fancy, but it gets the job done. All of the sheets are tables in the DataSet, so you just loop through the tables adding onto your destination. I'm outputting to a MongoDB, but I'm guessing you can swap that out for a StreamWriter for your CSV file rather easily.
private static void ImportValueSetAttributeFile(string filePath)
{
FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read);
// Reading from a OpenXml Excel file (2007 format; *.xlsx)
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
// DataSet - The result of each spreadsheet will be created in the result.Tables
DataSet result = excelReader.AsDataSet();
// Free resources (IExcelDataReader is IDisposable)
excelReader.Close();
var connectionString = ConfigurationManager.ConnectionStrings[0].ConnectionString;
var database = ConfigurationManager.AppSettings["database"];
var mongoAccess = new MongoDataAccess(connectionString, database);
var cdm = new BaseDataManager();
int ind = 0;
for (int i = 0; i < result.Tables.Count; i++)
{
int row_no = 1;
while (row_no < result.Tables[ind].Rows.Count) // ind is the index of table
// (sheet name) which you want to convert to csv
{
var currRow = result.Tables[ind].Rows[row_no];
var valueSetAttribute = new ValueSetAttribute()
{
CmsId = currRow[0].ToString(),
NqfNumber = currRow[1].ToString(),
ValueSetName = currRow[2].ToString(),
ValueSetOid = currRow[3].ToString(),
Definition = currRow[4].ToString(),
QdmCategory = currRow[5].ToString(),
Expansion = currRow[6].ToString(),
Code = currRow[7].ToString(),
Description = currRow[8].ToString(),
CodeSystem = currRow[9].ToString(),
CodeSystemOid = currRow[10].ToString(),
CodeSystemVersion = currRow[11].ToString()
};
cdm.AddRecords<ValueSetAttribute>(valueSetAttribute, "ValueSetAttributes");
row_no++;
}
ind++;
}
}

Download .xlsx file using Response.TransmitFile()

I'm working on some code that generates an Excel spreadsheet server-side and then downloads it to the user. I'm using ExcelPackage to generate the file.
The generation is working just fine. I can open the generated files using Excel 2007 with no issues. But, I'm having trouble downloading the file with Response.TransmitFile().
Right now, I have the following code:
//Generate the file using ExcelPackage
string fileName = generateExcelFile(dataList, "MyReportData");
Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");
Response.ContentType = "application/vnd.xls"
Response.Charset = "";
Response.TransmitFile(fileName);
When Excel 2007 opens the file downloaded as above, it gives the "file format doesn't match extension" warning. After clicking past the warning, Excel displays the raw xml contents of the file.
If I change the file extension, like so
Response.AddHeader("content-disposition", "attachment;filename=FileName.xlsx");
Excel 2007 gives an "Excel found unreadable content in the file" error, followed by a dialog that offers to locate a converter on the web. If I click "no" on this dialog, Excel is able to load the data.
I've also experimented with different MIME types, like application/vnd.ms-excel and application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, combined with file extensions of .xls and .xlsx. All combinations result in one of the two behaviors mentioned above.
What is the correct combination of file extension and MIME type to use in this scenario? What else could cause this failure, other than an improper MIME type or extension?
FYI, this is occurring with Visual Studio's built-in development web server. I haven't yet tried this with IIS.
I can't definitely say that there's anything wrong with your approach, but I'll just share some observations from doing something similar.
Headers are Pascal Case, most browsers shouldn't care but I would change your content-disposition to Content-Disposition. Changing the Charset shouldn't be necessary or relevant. Your content type should be fine, I would only use application/vnd.openxmlformats-officedocument.spreadsheetml.sheet and .xlsx if that is actually the content of the file, otherwise stick with application/vnd.ms-excel and .xls.
Another thing you should consider is sending the browser the Content-Length:
Response.AddHeader("Content-Length", new System.IO.FileInfo("FileName.xlsx").Length);
Also have you tried this with multiple browsers? Just wondering if it's a vendor-specific problem.
As a last ditch effort, you can set your Content-Type to application/octet-stream, and any browser should offer to download it, and then most browsers will let you open it after it's downloaded based on the extension.
use this
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=\"filename + ".zip" + "\"");
Response.TransmitFile(zipPath);
Response.Flush();
Response.Close();
Response.End();
in your code is
Response.AddHeader("content-disposition", "attachment;filename=\FileName.xlsx\");
Try like this
public void DataTableToExcel(DataTable dt, string Filename)
{
MemoryStream ms = DataTableToExcelXlsx(dt, "Sheet1");
ms.WriteTo(HttpContext.Current.Response.OutputStream);
HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + Filename);
HttpContext.Current.Response.StatusCode = 200;
HttpContext.Current.Response.End();
}
public static MemoryStream DataTableToExcelXlsx(DataTable table, string sheetName)
{
MemoryStream result = new MemoryStream();
ExcelPackage excelpack = new ExcelPackage();
ExcelWorksheet worksheet = excelpack.Workbook.Worksheets.Add(sheetName);
int col = 1;
int row = 1;
foreach (DataColumn column in table.Columns)
{
worksheet.Cells[row, col].Value = column.ColumnName.ToString();
col++;
}
col = 1;
row = 2;
foreach (DataRow rw in table.Rows)
{
foreach (DataColumn cl in table.Columns)
{
if (rw[cl.ColumnName] != DBNull.Value)
worksheet.Cells[row, col].Value = rw[cl.ColumnName].ToString();
col++;
}
row++;
col = 1;
}
excelpack.SaveAs(result);
return result;
}

Categories