Home > Mobile >  ASP.NET generated excel file has different format than extension
ASP.NET generated excel file has different format than extension

Time:11-15

I have a web application made in old asp.net 2.0. I need to generate excel file with specific formated table (the best way if I can load the template and only put data in code behind). To do this I'm trying to use this library CarlosAg.ExcelXmlWriter: http://www.carlosag.net/tools/excelxmlwriter/sample

And the final file is generated very well, but when I'm trying to open it in MS Excel warning popup appear with information that file has different format than the extension (xls). And also question if I want to open it if I trust the source of file. When I click yes, the file opened properly. On the other pc with different version of Excel, there's also warning, but different - file is broken and cannot be opened, the same in mobile (no possibility to open). What is interesting - I can open that file properly without any warnings in different office program, ex. WPS Office. So I make two steps back and try to open just simple file generated by the sample of Carlos library and effect is the same. Is there any chance to "fix" the file in code behind so MS Excel could also open it properly without any warnings?

    Dim book As Workbook = New Workbook()
    Dim sheet As Worksheet = book.Worksheets.Add("Sample")
    Dim row As WorksheetRow = sheet.Table.Rows.Add()
    row.Cells.Add("Hello World")
    book.Save("D:\Folder\test.xls")

CodePudding user response:

You have to give the file extension xlsx.

The older xls is in fact the legacy (closed) binary format of office files.

However, since office 2007, Microsoft has adopted a open xml format for ALL office documents (well, ok, outlook pst, and MS-Access are exceptions). In fact, if you take any office document (word, power-point, excel) etc., try renaming the xlsx document as a zip file. You find that you can now open the zip archive, and you can see/look at and even modify the xml in that document.

(do try this rename as a zip file for fun and giggles - you see how you actually don't even need any 3rd party tools to open, play with, and mess with the content in the zip archive (so, all office documents are in fact a simple zip archive!!!).

So, newer office file formats are in fact xml markup - and you can modify it!!

Anyway, without a doubt that library you are using thus uses the above feature/fact of office documents now being xml formatted and NOT a propriety Microsoft binary format - you can in fact modify such documents now on ANY computer that is able to open a zip file, and modify text files.

As a result, you are giving the document name a legacy binary file name (xls), but opening a xml formatted file (plain text), and thus Excel is detecting this fact/issue. So, you need to give that document the open office xml format extension (xlsx).

  • Related