I use CarlosAG-Dll which creates a XML-Excel-file for me (inside a MemoryStream).
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("content-disposition", "myfile.xml");
memory.WriteTo(Response.OutputStream);
My Problem here is, that I get at client side a myfile.xls (IE) or a myfile.xml.xls (FF) and therefore get an annoying security warning from excel.
I tried it as well with application/vnd.openxmlformats-officedocument.spreadsheetml.sheet (xlsx) but then it won’t even open.
So I need to either cut the .xml and send it as vnd.ms-excel (how?) or take another MIME-type (but which one?).
edit: I found a bug description here
I wonder if this is still open and why?
asked Nov 17, 2011 at 11:17
UNeverNoUNeverNo
5493 gold badges8 silver badges29 bronze badges
0
Use like this
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("content-disposition", "attachment; filename=myfile.xls");
For Excel 2007 and above the MIME type differs
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AppendHeader("content-disposition", "attachment; filename=myfile.xlsx");
See list of MIME types
Office 2007 File Format MIME Types
EDIT:
If the content is not a native Excel file format, but is instead a
text based format (such as CSV, TXT, XML), then the web site can add
the following HTTP header to their GET response to tell IE to use an
alternate name, and in the name you can set the extension to the right
content type:Response.AddHeader "Content-Disposition", "Attachment;Filename=myfile.csv"
For more details see this link
David Moles
46.7k27 gold badges133 silver badges231 bronze badges
answered Nov 17, 2011 at 11:52
PrasanthPrasanth
3,02930 silver badges44 bronze badges
5
If your document is an Excel Xml 2003 document, you should use the text/xml content type.
Response.ContentType = "text/xml";
Do not specifiy content-disposition.
This technichs works great with Handler, not with WebForm.
answered Jul 3, 2013 at 13:09
The security warning is NOT about the MIME type — it is a client-side security setting you can’t disable from the server side !
Another point — change Response.AppendHeader("content-disposition", "myfile.xml");
to:
Response.AppendHeader("content-disposition", "attachment; filename=myfile.xlsx");
OR
Response.AppendHeader("content-disposition", "inline; filename=myfile.xlsx");
For reference see http://www.ietf.org/rfc/rfc2183.txt
EDIT — as per comment:
IF the format is not XLSX (Excel 2007 and up) then use myfile.xls
in the above code.
answered Nov 17, 2011 at 11:22
YahiaYahia
69.2k9 gold badges113 silver badges144 bronze badges
3
MIME (Multipurpose Internet Mail Extensions) is a media type used to identify a type of data on the Internet or by applications. Its name contains the word «Internet» but it is not only limited to the Internet.IANA is in charge of standardizing and disseminating these MIME classifications.
There are numerous popular extensions available among them. One of them is the Excel MIME type.
Every mime type is divided into two parts, which are separated by a slash (/).
1 Type is a logical grouping of many MIME types that are similar to one another. All Excel files have an application as a type.
2 SubType is specific to a single file type within the «type«.They are unique within the «type».Some of the subtypes for excel files are: vnd.ms-excel,vnd.openxmlformats-officedocument.spreadsheetml.sheet,vnd.openxmlformats-officedocument.spreadsheetml.template,vnd.ms-excel.sheet.macroEnabled.12 etc.
There are various MIME types for Excel for various Excel-related files and their extensions such as. xls,.xlsx,.xlt,.xla, and so on.
Let’s look at Excel file MIME Type and extension used by them in table format.
Extension | MIME Type (Type / SubType) | Kind of Document |
.xls | application/vnd.ms-excel | Microsoft Excel |
.xlsx | application/vnd.openxmlformats-officedocument.spreadsheetml.sheet | Microsoft Excel (OpenXML) |
.xltx | application/vnd.openxmlformats-officedocument.spreadsheetml.template | Office Excel 2007 template |
.xlsm | application/vnd.ms-excel.sheet.macroEnabled.12 | Office Excel 2007 macro-enabled workbook |
.xltm | application/vnd.ms-excel.template.macroEnabled.12 | Office Excel 2007 macro-enabled workbook template |
.xlam | application/vnd.ms-excel.addin.macroEnabled.12 | Office Excel 2007 macro-enabled add-in |
.xlsb | application/vnd.ms-excel.sheet.binary.macroEnabled.12 | Office Excel 2007 non xml binary workbook |
Let’s explain them in brief.
1 .xls
.xls is one of the older file extension of Microsoft Excel Spreadsheet.It is created by Excel 97 or Excel 2003. They by default generate .xls format.
MIME Type Supported by .xls file is application/vnd.ms-excel where the application of MIME type and vnd.ms-excel is subtypes and vnd here means vendor-specific which in this case vendor is Microsoft.
If you have an.xls file and want to open it in Excel before prior 2007, you can do so easily because Excel before 2007 recognizes application/vnd.ms-excel and does not require to afford to open it.
Despite the fact that the.xls file format is older, it can be opened in all versions of Excel due to backward compatibility in newer versions.
2 .xlsx
xlsx is the new file extension of the Microsoft Excel Spreadsheet. It is created by Excel 2007 and later versions.
If you create an excel file in Excel 2007 or later, it will be saved with the.xlsx extension by default; however, you can also save the same file in.xls format.xlsx is more secure and better for data storage(ie. smaller file size) than xls.
MIME type for .xlsx file is application/vnd.openxmlformats-officedocument.spreadsheetml.sheet where MIME type is application and subtype is vnd.openxmlformats-officedocument.spreadsheetml.sheet
It is a file format based on Office OPEN XML developed by Microsoft for representing spreadsheets. Because xlsx is an open standard, other software application vendors, such as Google (Google Sheets), can use it to interoperate with their spreadsheet applications.
📑 The last «x» in the xlsx file extension indicates that the file is based on the XML Standard.
You can open Xls file in excel 2007 and later and convert them to xlsx and save it.
3 .xltx
Microsoft Excel Template files with the. xltx extensions are based on the Office OpenXML file format specifications. It is used to generate a standard template file that can be used to generate XLSX files with the same settings as the XLTX file.
MIME type for .xlsx file is application/vnd.openxmlformats-officedocument.spreadsheetml.template where MIME type is application and subtype is vnd.openxmlformats-officedocument.spreadsheetml.sheet
It is XML based file format developed by Microsoft for representing templates. An XLTX is identical to an XLSX in every way except that Excel creates a new instance of an XLSX if the file opened is an XLTX.
📓 xltx is the replacement for the old .xlt format.
4 .xlsm
An XLSM file is a macro-enabled spreadsheet created by Microsoft Excel that can also be opened with Google Sheets.XLSM files are based on the Office Open XML format, where the last «m» of an xlsm file extension indicates that the file contains macros.Macros can be stored within an xlsm file, allowing users to automate repetitive tasks.
MIME type for .xlsx file is application/vnd.ms-excel.sheet.macroEnabled.12 where MIME type is application and subtype is vnd.ms-excel.sheet.macroEnabled.12
5 .xlam
An XLAM file extension indicates an Excel Macro-Enabled Add-In file, which is used to provide additional functionality for spreadsheets.
It has the following MIME types:application/vnd.ms-excel.template.macroEnabled.12 where MIME type is application and subtype is vnd.ms-excel.template.macroEnabled.12
Because of the file’s purpose, there is built-in macro support in .xlam files.
6 .xlsb
An XLSB file is an Excel Binary Workbook file that stores data in binary rather than XML format. Because they are stored in binary, the read and write times in xlsb files are faster, and they have been found to be useful for very large and complex spreadsheets for this reason. They are also smaller in size than the XLSM format.
MIME type for .xlsx file is application/vnd.ms-excel.sheet.binary.macroEnabled.12 where MIME type is application and subtype is vnd.ms-excel.sheet.binary.macroEnabled.12
FAQ:
How to generate .xls file in C# ?
For generating a .xls file in C# code you have to mention application/vnd.ms-excel MIME types in response header as shown below.
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("content-disposition", "attachment; filename=sample.xls");
How to generate .xlsx file in C#?
For generating a .xls file in C# code you have to mention application/vnd.openxmlformats-officedocument.spreadsheetml.sheet MIME types in response header as shown below.
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AppendHeader("content-disposition", "attachment; filename=sample.xls");
If you are generating Excel file target to xlsx file then you have to use above.
What is the replacement of the xla format?
Ans: xlam is the replacement for the old .xla format.
This topic lists the most common MIME types with corresponding document types, ordered by their common extensions.
The following two important MIME types are the default types:
text/plain
is the default value for textual files. A textual file should be human-readable and must not contain binary data.application/octet-stream
is the default value for all other cases. An unknown file type should use this type. Browsers are particularly careful when manipulating these files to protect users from software vulnerabilities and possible dangerous behavior.
IANA is the official registry of MIME media types and maintains a list of all the official MIME types. This table lists important MIME types for the Web:
Extension | Kind of document | MIME Type |
---|---|---|
.aac |
AAC audio | audio/aac |
.abw |
AbiWord document | application/x-abiword |
.arc |
Archive document (multiple files embedded) | application/x-freearc |
.avif |
AVIF image | image/avif |
.avi |
AVI: Audio Video Interleave | video/x-msvideo |
.azw |
Amazon Kindle eBook format | application/vnd.amazon.ebook |
.bin |
Any kind of binary data | application/octet-stream |
.bmp |
Windows OS/2 Bitmap Graphics | image/bmp |
.bz |
BZip archive | application/x-bzip |
.bz2 |
BZip2 archive | application/x-bzip2 |
.cda |
CD audio | application/x-cdf |
.csh |
C-Shell script | application/x-csh |
.css |
Cascading Style Sheets (CSS) | text/css |
.csv |
Comma-separated values (CSV) | text/csv |
.doc |
Microsoft Word | application/msword |
.docx |
Microsoft Word (OpenXML) | application/vnd.openxmlformats-officedocument.wordprocessingml.document |
.eot |
MS Embedded OpenType fonts | application/vnd.ms-fontobject |
.epub |
Electronic publication (EPUB) | application/epub+zip |
.gz |
GZip Compressed Archive | application/gzip |
.gif |
Graphics Interchange Format (GIF) | image/gif |
.htm , .html |
HyperText Markup Language (HTML) | text/html |
.ico |
Icon format | image/vnd.microsoft.icon |
.ics |
iCalendar format | text/calendar |
.jar |
Java Archive (JAR) | application/java-archive |
.jpeg , .jpg |
JPEG images | image/jpeg |
.js |
JavaScript | text/javascript (Specifications: HTML and RFC 9239) |
.json |
JSON format | application/json |
.jsonld |
JSON-LD format | application/ld+json |
.mid , .midi |
Musical Instrument Digital Interface (MIDI) | audio/midi , audio/x-midi |
.mjs |
JavaScript module | text/javascript |
.mp3 |
MP3 audio | audio/mpeg |
.mp4 |
MP4 video | video/mp4 |
.mpeg |
MPEG Video | video/mpeg |
.mpkg |
Apple Installer Package | application/vnd.apple.installer+xml |
.odp |
OpenDocument presentation document | application/vnd.oasis.opendocument.presentation |
.ods |
OpenDocument spreadsheet document | application/vnd.oasis.opendocument.spreadsheet |
.odt |
OpenDocument text document | application/vnd.oasis.opendocument.text |
.oga |
OGG audio | audio/ogg |
.ogv |
OGG video | video/ogg |
.ogx |
OGG | application/ogg |
.opus |
Opus audio | audio/opus |
.otf |
OpenType font | font/otf |
.png |
Portable Network Graphics | image/png |
.pdf |
Adobe Portable Document Format (PDF) | application/pdf |
.php |
Hypertext Preprocessor (Personal Home Page) | application/x-httpd-php |
.ppt |
Microsoft PowerPoint | application/vnd.ms-powerpoint |
.pptx |
Microsoft PowerPoint (OpenXML) | application/vnd.openxmlformats-officedocument.presentationml.presentation |
.rar |
RAR archive | application/vnd.rar |
.rtf |
Rich Text Format (RTF) | application/rtf |
.sh |
Bourne shell script | application/x-sh |
.svg |
Scalable Vector Graphics (SVG) | image/svg+xml |
.tar |
Tape Archive (TAR) | application/x-tar |
.tif , .tiff |
Tagged Image File Format (TIFF) | image/tiff |
.ts |
MPEG transport stream | video/mp2t |
.ttf |
TrueType Font | font/ttf |
.txt |
Text, (generally ASCII or ISO 8859-n) | text/plain |
.vsd |
Microsoft Visio | application/vnd.visio |
.wav |
Waveform Audio Format | audio/wav |
.weba |
WEBM audio | audio/webm |
.webm |
WEBM video | video/webm |
.webp |
WEBP image | image/webp |
.woff |
Web Open Font Format (WOFF) | font/woff |
.woff2 |
Web Open Font Format (WOFF) | font/woff2 |
.xhtml |
XHTML | application/xhtml+xml |
.xls |
Microsoft Excel | application/vnd.ms-excel |
.xlsx |
Microsoft Excel (OpenXML) | application/vnd.openxmlformats-officedocument.spreadsheetml.sheet |
.xml |
XML | application/xml is recommended as of RFC 7303 (section 4.1), but text/xml is still used sometimes. You can assign a specific MIME type to a file with .xml extension depending on how its contents are meant to be interpreted. For instance, an Atom feed is application/atom+xml , but application/xml serves as a valid default. |
.xul |
XUL | application/vnd.mozilla.xul+xml |
.zip |
ZIP archive | application/zip |
.3gp |
3GPP audio/video container | video/3gpp ; audio/3gpp if it doesn’t contain video |
.3g2 |
3GPP2 audio/video container | video/3gpp2 ; audio/3gpp2 if it doesn’t contain video |
.7z |
7-zip archive | application/x-7z-compressed |
Я использую CarlosAG-Dll, который создает для меня файл XML-Excel (внутри MemoryStream).
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("content-disposition", "myfile.xml");
memory.WriteTo(Response.OutputStream);
Моя проблема здесь в том, что я получаю на стороне клиента файл myfile.xls(IE) или myfile.xml.xls(FF) и поэтому получаю раздражающее предупреждение безопасности от excel.
Я попробовал это также с application/vnd.openxmlformats-officedocument.spreadsheetml.sheet(xlsx), но потом он даже не откроется.
Так что мне нужно либо вырезать .xml, либо отправить его как vnd.ms-excel (как?) или взять другой MIME-тип (но какой?).
edit: Я нашел описание ошибки здесь
Интересно, это все еще открыто и почему?
17 нояб. 2011, в 13:04
Поделиться
Источник
3 ответа
Используйте это как
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("content-disposition", "attachment; filename=myfile.xls");
Для Excel 2007 и выше тип MIME отличается
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AppendHeader("content-disposition", "attachment; filename=myfile.xlsx");
См. список типов MIME
Формат MIME файлов формата Office 2007
EDIT:
Если содержимое не является собственным файлом формата Excel, но вместо этого текстовый формат (например, CSV, TXT, XML), затем веб-сайт может добавить следующий HTTP-заголовок для ответа GET, чтобы сообщить IE использовать альтернативное имя, а в имени вы можете установить расширение вправо тип контента:
Response.AddHeader "Content-Disposition", "Attachment;Filename=myfile.csv"
Подробнее см. эта ссылка
Prasanth
17 нояб. 2011, в 13:49
Поделиться
Если ваш документ является документом Excel Xml 2003, вы должны использовать тип содержимого text/xml.
Response.ContentType = "text/xml";
Не указывайте расположение содержимого.
Этот technichs отлично работает с Handler, а не с WebForm.
Franky
03 июль 2013, в 14:47
Поделиться
Предупреждение о безопасности не относится к типу MIME — это параметр безопасности на стороне клиента, который нельзя отключить со стороны сервера!
Другая точка — измените Response.AppendHeader("content-disposition", "myfile.xml");
на:
Response.AppendHeader("content-disposition", "attachment; filename=myfile.xlsx");
ИЛИ
Response.AppendHeader("content-disposition", "inline; filename=myfile.xlsx");
Для справки см. http://www.ietf.org/rfc/rfc2183.txt
EDIT — в соответствии с комментарием:
Если формат не XLSX (Excel 2007 и выше), используйте myfile.xls
в приведенном выше коде.
Yahia
17 нояб. 2011, в 11:24
Поделиться
Ещё вопросы
- 0добавить div в JQuery с кавычками в поле
- 1Заменить снимок с определителем Tycho
- 1Более 79 символов в строке с комментарием
- 0Как я могу изменить свойства обещания, чтобы они были равны свойствам объекта в AngularJS?
- 1Java итеративное углубление на дереве без рекурсии
- 0Доступ к php global в шаблоне веток
- 1Vue — как периодически обновлять значение в представлении с помощью фильтра
- 0Обработка массивов
- 0Удалить последнюю запятую из значения массива в цикле
- 0Присвоение второго указателя объекту, указанному первым указателем
- 0Эффективная проверка, если значение существует в базе данных
- 1Как открыть навигационный ящик справа налево [продублировать]
- 0Хитрая структура указатель итерация без предоставления дампа
- 1Как автоматически получить оставшуюся память при профилировании в автономном режиме JProfiler с помощью триггеров
- 0Массив классов структур не инициализируется должным образом
- 1Получить Float ИЛИ целочисленное значение из строки в Java
- 0PHP безопасная система загрузки
- 0Проверка данных с использованием Parsley не работает
- 1Как сгруппировать блок кода в Python, похожий на функцию, но без необходимости определения параметров?
- 1Regex Parsing Начало строки
- 0Пользовательский альпийский образ mysql не загружает файл init.sql из подключенного docker-entrypoint-initdb.d как том
- 0скрытая ошибка ссылки g ++
- 1Spring + Hibernate SQL имя объекта не разрешено
- 1Angular: компонент из общего модуля не распознается
- 1Android Studio не компилируется
- 0Как получить обновления базы данных MySQL для запуска повторной аутентификации в сеансах PHP
- 0Angularjs предел, чтобы не работать в нг-повтор
- 0Двусторонняя сортировка / несортировка с помощью перетаскивания с помощью пользовательского интерфейса JQuery
- 1Как конвертировать LINQ вложенные Selectmany в регулярные операторы SQL
- 0Как сделать разрыв между строками в FlowPanel в Css в Gwt?
- 0Защита исходного кода AngularJS
- 0Угловая, встроенная логика привязки
- 1Выполнить команду с правами суперпользователя в методе JNI в Android
- 1Как я могу получить имя файла запущенного в данный момент процесса?
- 0CodeIgniter нумерация страниц не работает с многоязычным сайтом
- 1Почему toFixed () принимает от 0 до 20 цифр
- 1Лучший способ инициализировать трехмерный список
- 0Невозможно скомпилировать с собственной библиотекой
- 0Написание перегруженного оператора присваивания
- 1Недостатки сохранения файловых дескрипторов открыты?
- 0Как я могу создать фиксированный заголовок таблицы
- 1InstallUtil какая версия фреймворка использовалась для установки сервиса?
- 0Десериализация веб-API ajax опубликовала нулевые значения в виде «нулевой» строки
- 1Как настроить ProGuard, чтобы уважать модель Джексона?
- 0Пользователь посещает события на Facebook с PHP API 3.2.3
- 0jQuery — Ajax отправляет данные JSON в GET
- 1Datagrid ComboBox связывает два значения
- 0Скрипты Jquery на слайдах внешней страницы медленно загружаются или останавливаются. Что я делаю?
- 0MongoDB: вставка и обновление в массиве
- 0Экспорт заказов Magento — получение суммы скидки