File application vnd ms excel

MS Excel has the following observed MIME types:

  • application/vnd.ms-excel (official)
  • application/msexcel
  • application/x-msexcel
  • application/x-ms-excel
  • application/x-excel
  • application/x-dos_ms_excel
  • application/xls
  • application/x-xls
  • application/vnd.openxmlformats-officedocument.spreadsheetml.sheet (xlsx)

Is there any one type that would work for all versions? If not, do we need to set response.setContentType() with each one of these mime types individually?

Also, we use file streaming in our application to display document (not just excel — any type of document). In doing so, how can we retain the filename if the user opts to save the file — currently, the name of the servlet that renders the file appears as the default name.

Jordy van Eijk's user avatar

asked Jun 10, 2009 at 7:07

Subramanian's user avatar

5

I believe the standard MIME type for Excel files is application/vnd.ms-excel.

Regarding the name of the document, you should set the following header in the response:

header('Content-Disposition: attachment; filename="name_of_excel_file.xls"');

Callum Watkins's user avatar

answered Dec 26, 2009 at 19:44

jbochi's user avatar

jbochijbochi

28.7k16 gold badges73 silver badges90 bronze badges

7

Waking up an old thread here I see, but I felt the urge to add the «new» .xlsx format.

According to http://filext.com/file-extension/XLSX the extension for .xlsx is application/vnd.openxmlformats-officedocument.spreadsheetml.sheet. It might be a good idea to include it when checking for mime types!

Dave Jarvis's user avatar

Dave Jarvis

30.2k39 gold badges178 silver badges312 bronze badges

answered Apr 20, 2012 at 12:39

Karlis Rode's user avatar

Karlis RodeKarlis Rode

3,5932 gold badges16 silver badges16 bronze badges

1

For .xls use the following content-type

application/vnd.ms-excel

For Excel 2007 version and above .xlsx files format

application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

answered Apr 6, 2019 at 7:21

Du-Lacoste's user avatar

Du-LacosteDu-Lacoste

11k2 gold badges65 silver badges50 bronze badges

I was setting MIME type from .NET code as below —

File(generatedFileName, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")

My application generates excel using OpenXML SDK. This MIME type worked —

vnd.openxmlformats-officedocument.spreadsheetml.sheet

Aleksei Matiushkin's user avatar

answered Jun 21, 2016 at 17:01

Divyans Mahansaria's user avatar

I am using EPPlus to generate .xlsx (OpenXML format based) excel file. For sending this excel file as attachment in email I use the following MIME type and it works fine with EPPlus generated file and opens properly in ms-outlook mail client preview.

string mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
System.Net.Mime.ContentType contentType = null;
if (mimeType?.Length > 0)
{
    contentType = new System.Net.Mime.ContentType(mimeType);
}

answered Nov 1, 2018 at 11:25

Vishwajit G's user avatar

Vishwajit GVishwajit G

5004 silver badges9 bronze badges

For anyone who is still stumbling with this after using all of the possible MIME types listed in the question:

I have found that iMacs tend to also throw a MIME type of «text/xls» for XLS Excel files, hope this helps.

answered May 25, 2016 at 18:58

be_es's user avatar

be_esbe_es

311 bronze badge

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

various-format-of-excel-file

fig. various format for saving excel file

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.

Содержание

  1. What is MIME Type for Excel Document ?
  2. 1 .xls
  3. 2 .xlsx
  4. 3 .xltx
  5. 4 .xlsm
  6. 5 .xlam
  7. 6 .xlsb
  8. Content type excel
  9. Установка типа mime для документа excel
  10. 7 Ответов
  11. Похожие вопросы:
  12. Загрузка файлов xls или xlsx с помощью codeigniter, ошибка типа mime
  13. 4 ответов
  14. PHP библиотека PHPExcel для работы с Excel
  15. What is MIME application/excel?
  16. application/excel
  17. What Are MIME Types?
  18. Why Do I Need MIME Types Like application/excel?
  19. What Are The Most Common Problems Associated With application/excel?
  20. How To Fix application/excel Issues
  21. Do I have the application/excel “player application” installed?
  22. Do I have broken application/excel file associations?
  23. phpexcel: писать данные в Excel с помощью PHP и читать из Excel

What is MIME Type for Excel Document ?

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.

Please enable JavaScript

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

fig. various format for saving excel file

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.

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.

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

For generating a .xls file in C# code you have to mention application/vnd.ms-excel MIME types in response header as shown below.

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.

If you are generating Excel file target to xlsx file then you have to use above.

Ans: xlam is the replacement for the old .xla format.

Источник

Content type excel

Установка типа mime для документа excel

MS Excel имеет следующие наблюдаемые типы MIME:

  • application/vnd.ms-excel (официальный)
  • application/msexcel
  • application/x-msexcel
  • application/x-ms-excel
  • application/x-excel
  • application/x-dos_ms_excel
  • application/xls
  • application/x-xls
  • application/vnd.openxmlformats-officedocument.spreadsheetml.sheet (XLSX-файл)

Есть ли какой-то один тип, который будет работать для всех версий? Если нет, то нужно ли устанавливать response.setContentType() для каждого из этих типов mime отдельно?

Кроме того, мы используем потоковую передачу файлов в нашем приложении для отображения документа (а не только excel — любого типа документа). При этом, как мы можем сохранить имя файла, если пользователь решает сохранить файл — в настоящее время имя сервлета, который отображает файл, отображается как имя по умолчанию.

7 Ответов

Я считаю, что стандартный тип MIME для файлов Excel — это application/vnd.ms-excel .

Что касается названия документа, то в ответе следует задать следующий заголовок:

Здесь я вижу просыпающуюся старую нить, но я почувствовал желание добавить формат «new» .xlsx.

Согласно http://filext.com/file-extension/XLSX расширение для .xlsx равно application/vnd.openxmlformats-officedocument.spreadsheetml.sheet . Это может быть хорошей идеей, чтобы включить его при проверке на наличие типов mime!

Вы всегда должны использовать тип ниже MIME, если вы хотите обслуживать файл excel в формате xlsx

Я устанавливал тип MIME из кода .NET, как показано ниже —

Мое приложение генерирует excel, используя OpenXML SDK. Этот тип MIME работал —

Для .xls используйте следующий тип содержимого

Для версии Excel 2007 и выше формат файлов .xlsx

Я использую EPPlus для создания файла .xlsx (на основе формата OpenXML) excel. Для отправки этого файла excel в качестве вложения в email я использую следующий тип MIME, и он отлично работает с EPPlus сгенерированным файлом и правильно открывается в MS-outlook mail client preview.

Для тех, кто все еще спотыкается с этим после использования всех возможных типов MIME, перечисленных в вопросе:

Я обнаружил, что iMacs, как правило, также бросает MIME тип «text/xls» для файлов XLS Excel, надеюсь, это поможет.

Похожие вопросы:

Таким образом, в CouchDB вы можете предположительно изменить типы mime. В футоне вам просто нужно пойти и отредактировать источник документа и изменить поле content_type на вложения в поле.

Невозможно получить тип MIME из bytearray-возвращает NULL для любого документа типа MIME. byte[] res.

Как я могу установить правильный тип MIME, который работает с excel 2007? прямо сейчас у меня есть это: header(Content-type: application/vnd.ms-excel; charset=UTF-8); мой браузер постоянно говорит.

Проверка типа mime в php довольно проста, но, насколько я знаю, mime можно подделать. Злоумышленник может загрузить сценарий php, например, с типом jpeg mime. Одна вещь, которая приходит на ум, это.

Я пытаюсь развернуть сайт Jekyll. Вот вам и поток: Содержимое добавляется и перемещается в BitBucket BitBucket трубопровод строит сайт Находит все файлы HTML в _site/ и удаляет их расширение.

Кроме LSCopyDefaultApplicationURLForURL существует LSCopyApplicationURLsForURL , чтобы получить все приложения, а не только один по умолчанию. Если вы просто хотите получить приложения по умолчанию.

Я хочу написать excel и отправить его пользователю в качестве ответа в приложении с помощью Play framework 1.x . Но я не уверен, как установить ответ content-type/MIME-type для возврата doc или.

Для веб-приложения, которое позволяет просматривать документы в браузере, я хотел бы проверить, поддерживает ли браузер пользователя предварительный просмотр текущего типа mime документа. Существует.

Существует ли официальный URN для типа MIME? Mozilla Firefox и другие приложения используют обозначения типа urn:mimetype:text/plain или urn:mimetype:handler:text/plain . Есть две проблемы с этим.

Загрузка файлов xls или xlsx с помощью codeigniter, ошибка типа mime

Ну, я считаю, что это не проблема Codeigniter per se как это mime-type.

Я пытаюсь загрузить файл, файл xls (или xlsx) и MIME-тип браузера, а отчет php —приложения/октет-поток вместо приложение / excel, application / vnd.ms-excel или приложения/msexcel для файла xls. Конечно, плагин загрузки codeigniter сообщит об ошибке (недопустимый тип файла), поскольку он пытается сопоставить расширение файла с типом mime.

странная (est) вещь может заключаться в том, что один и тот же код работал в течение нескольких месяцев и теперь перестал работать с последними Chrome (16.0.912.77), Firefox (10.0) и IE9.

У кого-нибудь была такая же (или похожая) проблема и желание поделиться решением?

большое спасибо. PS: Я не буду предоставлять код, поскольку это не совсем код, но при необходимости я загружу некоторые фрагменты.

редактировать

Это может быть актуально: ошибка не происходит с теми же браузерами в аналогичной конфигурации, но с MS Office вместо Libre Office (на моем ПК). Это также не происходит в системе GNU / Linux + Libre Office. Итак, может ли это быть Windows, играющая жестко на наборе с открытым исходным кодом, или офис Libre меняет типы mime просто для этого?

4 ответов

Я также получаю эту ошибку.

CI сообщает тип файла «application / zip», который имеет смысл, поскольку формат xlsx является сжатым форматом (переименуйте его в zip, и вы можете открыть содержимое).

Я добавил / заменил следующую строку в файл типов mime (application/config/mimes.php):

и это работает (по крайней мере, для этого браузера!)

пожалуйста, пройдите через следующее описание и подсказку и получите ответ легко!

описание:

на самом деле, как многие из них посоветовали добавить/заменить следующую строку в файле (application/config/mimes.php):

Но я понял это в CodeIgniter Версии 2.2.* проблема немного отличается! Они уже добавили эту строку, но забыли добавить следующий «file_type» ==> ‘application / vnd.ms-excel’

Итак, добавив выше ‘ application / vnd.ms-excel’ в массив xlsx тип файла, позвольте мне загрузить .XLSX-файл файлы!

подсказка:

всякий раз, когда вы получаете следующую ошибку, на платформе CodeIgniter и загружаете файлы:

тип файла, который вы пытаетесь загрузить, не допускается.

сделайте следующее в вашем Метод загрузки контроллера,

и это даст вам огромный массив, который вы можете получить представление из этого ссылке.(Пожалуйста, смотрите конец этой страницы). В этом массиве вы можете получить реальный mime_type файла, который вы пытаетесь загрузить, но не даете вам загрузить.

ответ:

в моем случае, расширение файла, .XLSX-файл, а тип мима был application / vnd.ms-excel, который был не добавлено в

так что я добавил его вручную, и после этого он работает ВЕРРИ ХОРОШО.

то же самое произошло с загрузкой CSV еще раз, когда я проверил расширение файла .csv но тип mime был text / plain, когда я добавил его в следующую строку:

и сохраненный следующим образом:

это работает как шарм! :Д Попробуйте, если вы найдете что-то новое в вышеприведенном шаги, пожалуйста, прокомментируйте здесь. Поэтому, надеясь, что это будет полезно для всего сообщества CodeIgniter, я разместил его некоторое время!

С наилучшими пожеланиями, ребята,

это была ошибка CI несколько месяцев назад:https://github.com/EllisLab/CodeIgniter/issues/394 . пантомимы.php в фреймворке был обновлен и ошибка была устранена. Обновите библиотеку CodeIgniter до версии 2.1.0 (или новее).

также хорошей вещью для тестирования / дампа являются типы mime вашего сервера.

Другой альтернативой является принуждение типа mime. С.htaccess, это было бы

для всего приключения отладки, испытайте различные файлы офиса с get_mime_by_extension($file) С помощью Помощника по файлам (http://codeigniter.com/user_guide/helpers/file_helper.html)

только для записей, я нашел причину, MIME-тип отсутствовал в реестре windows, решил добавить эти ключи с a .reg-файл:

но предпочел бы использовать эти решения, я не люблю возиться с реестром.

PHP библиотека PHPExcel для работы с Excel

Для работы с Excel использовал библиотеку PHPExcel. Установка простейшая – кладем папку Classes в нужную папку на сервере, указываем корректные пути в include/require.

Примеры кода по чтению/генерации файлов Excel можно посмотреть на github странице библиотеки.

Красивости

и этим не ограничивается функционал, это лишь то, что использовал:

  • mergeCells(“cell_range”) – Объединение указанных ячеек в одну. Данные должны лежать в первой ячейке, иначе они теряются.
  • setSize(16) – Делаем размер шрифта 16 для указанных ячеек.
  • setBold(true) – Делаем текст “жирным”
  • setWrapText(true) – Делаем перенос слов по умолчанию для всех ячеек
  • setAutoFilter – Включить фильтр по умолчанию
  • freezePane – Закрепить какие либо строки, например первую
  • borders – делается через создание стиля, а потом его применение на указанный диапазон ячеек
  • color – Аналогично с помощью стилей меняем цвет шрифта (Font)
  • setARGB – Изменить цвет ячейки, например
    • всей первой строки
    • конкретной ячейки (делал так цвет был переменным и задавался на основе данных – формировался разноцветный показательный Excel)
    • диапазона ячеек по диагонали
ЧТЕНИЕ

Код для чтения (два столбца):

Редактирование

Открываем файл test.xlsx, на его основе создаем новый new.xlsx с измененными парой ячеек.

ГЕНЕРАЦИЯ

Пример генерации на основе результата MySQL (не тестил, использовал универсальную функцию ниже).

Если нужно протестить базовую работу генерации на основе двумерного массива

Пример генерации xls из двумерного массива с настройками

  • имени (определяется на основе значения в переменной $_POST[‘filename’]),
  • ширины столбца (на основе $_POST[‘excelSettings’]),
  • bold первой строки (setBold),
  • переноса слов (setWrapText).

Пример вызова и код по генерации кнопки, добавлению к названию файла даты/времени (формат 20170123_003800_Название.xlsx) и переходу на страницу генерации xls.

Вызов функции (про функцию iconv_for_xls ниже):

Особенности

Мусор

Нужно очень внимательно смотреть, чтобы php не генерировал никакого вывода, в противном случае возможны разные ошибки и искажения файла.

Например, возможны кракозябры при генерации файла больше 20-40 строк, если оставить включенным debug типа print_r($_POST); (почему не воспроизводиться при генерации мелких файлов – это вопрос :)).

Аналогично, будет выдавать ошибку:

  1. Если в конце кода php нет “exit;”
  2. Если перед генерацией файла нет очистки буфера вывода через “ob_end_clean();”
  3. Если используется генерация xlsx (Excel2007), но не установлены xml и xmlwriter модули PHP. Так же может выдаваться ошибка “Fatal error: Class ‘XMLWriter’ not found in /

/XMLWriter.php on line 37” т.к. библиотека PHPExcel использует наследование класса от XMLWriter (“class PHPExcel_Shared_XMLWriter extends XMLWriter”), т.е. требует установленного модуля xmlwriter. Для “нормальных” дистрибутивов это делается простым sudo apt-get/yum install php-xmlwriter (или php5-xml) и перезагрузкой apache, для gentoo это делается через пересборку всего php с новым модулем.

Отправка array на другую страницу

Чтобы функция по генерации xlsx была универсальной, сделал отдельную страницу по генерации, но на эту страницу потребовалось передать двумерный массив. В интернете гуляет два варианта решения: сохранить массив в сессии/куках, передать его через json (лучше) или serialize (хуже).

Через сессии все передавалось, только значение почему то не апдейтилось корректно. Сходу не разобрался в причинах, использовал сначала serialize (полный пример см. в function create_xls), но потом мигрировал на json из-за периодических проблем со спец. символами serialize.

Кодировка

Если на сайте кодировка cp-1251, то при генерации обязательно нужно использовать iconv в utf-8. В противном случае вместо русских символов в ячейке будет бред (например, “ИСТИНА”).

What is MIME application/excel?

application/excel

Compatible with Windows 10, 8, 7, Vista, XP and 2000

Optional Offer for WinThruster by Solvusoft | EULA | Privacy Policy | Terms | Uninstall

What Are MIME Types?

A Multi-Purpose Internet Mail Extension (eg. “application/excel”), also known as a MIME, is type of Internet standard originally developed to allow the exchange of different types of data files through e-mail messages. MIME types like application/excel are classified into specific data categories such as Video, Audio, Image, and many more. This categorization provides instructions to your computer or mobile device about how these files should be opened / viewed.

Why Do I Need MIME Types Like application/excel?

Categorizing MIME types like application/excel into a data type such as “Application” allows your e-mail client or Internet browser to display the content as intended. For example, when you attach a digital camera photo file to an e-mail, an Image MIME type will be associated with that file to allow your recipient to view the photograph.

Here’s how it works: Web servers (computers that host websites and e-mail) insert a set of MIME instructions into the beginning of a data transmission, such as an e-mail message or webpage, in the following format:

Content-Type: application/excel

[Format Explanation: The MIME type, which in this example is “Application”, is separated by a forward slash (“/”) and followed by a subtype.]

This set of instructions tells your client application, such as an e-mail program (eg. Microsoft Outlook, Apple Mail) or web browser (eg. Google Chrome, Mozilla Firefox), which “player application” should be used to properly display the application/excel content.

Many modern web browsers include built-in components to display common data types such as image players (eg. GIF, JPEG), Adobe Flash Player, Javascript, and many more. Other less-common types of players must be downloaded separately in order to properly display the MIME content.

What Are The Most Common Problems Associated With application/excel?

Sometimes you’ll find that your web browser or e-mail client is unable to properly display your application/excel content. This could be due to one of two reasons:

1. You are missing the proper Application “player software” to display the application/excel content.

2. Your Windows Registry contains an incorrect file extension (eg. XLS, PDF) association with the application/excel MIME type.

How To Fix application/excel Issues

Do I have the application/excel “player application” installed?

The first step in troubleshooting issues with opening application/excel content is to first make sure that you have the correct “player application” installed for this MIME type. Because there can be several (or even hundreds) of related software applications to application/excel, it is very difficult for us to compile a comprehensive list.

Therefore, a key strategy in determining the correct application is to look for clues on what software programs might be related to application/excel. Look at the naming of the subtype for clues about a related program (eg. Word, Excel) or software developer name (eg. Microsoft).

Furthermore, if you’ve been sent MIME type application/excel as an e-mail attachment, look for the file extension of the attached file. This file extension (eg. XLT, XLS, etc.) can provide you with a clue of what “player application” is associated with this Application MIME. Take a look at our file extension list below to see if there are any clues to finding the right “player application”.

Do I have broken application/excel file associations?

The second step in troubleshooting application/excel issues is making sure that you have correct file associations in the Windows Registry. Installing and uninstalling programs can lead to incorrect file associations with application/excel. Take a look at your Windows Registry settings to ensure that the MIME type is correctly associated with the “player application” and file extension.

WARNING: DO NOT edit the Windows Registry unless you are an advanced computer user with experience editing the Registry. Making an error in editing the Registry can create irreversible damage to your PC.

If you are not comfortable editing the Windows Registry, we highly recommend using an automated registry cleaning program, or taking you computer to a qualified professional.

phpexcel: писать данные в Excel с помощью PHP и читать из Excel

Задача писать данные в Excel с помощью PHP и читать из Excel

Как сказал Гагарин — «Поехали!»

//Скачать библиотеку — http://phpexcel.codeplex.com/
//Нашел русскую документацию — http://www.cyberforum.ru/php-beginners/thread1074684.html
//Подключаем скачаную библиотеку
include(«Classes/PHPExcel.php»);

//Создание объекта класса библиотеки
$objPHPExcel = new PHPExcel();

//Указываем страницу, с которой работаем
$objPHPExcel->setActiveSheetIndex(0);

//Получаем страницу, с которой будем работать
$active_sheet = $objPHPExcel->getActiveSheet();

//Создание новой страницы(пример)
//$objPHPExcel->createSheet();

//Ориентация и размер страницы
// $active_sheet->getPageSetup()
// ->setOrientation(PHPExcel_Worksheet_PageSetup::ORIENTATION_PORTRAIT);
$active_sheet->getPageSetup()
->setOrientation(PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE);
$active_sheet->getPageSetup()
->setPaperSize(PHPExcel_Worksheet_PageSetup::PAPERSIZE_A4);

//Имя страницы
$active_sheet->setTitle(«Данные из docs»);

//Ширина стобцов
$active_sheet->getColumnDimension(‘A’)->setWidth(8);
$active_sheet->getColumnDimension(‘B’)->setWidth(10);
$active_sheet->getColumnDimension(‘C’)->setWidth(90);

//Объединение ячеек
$active_sheet->mergeCells(‘A1:C1’);

//Высота строки
$active_sheet->getRowDimension(‘1’)->setRowHeight(30);

//Вставить данные(примеры)
//Нумерация строк начинается с 1, координаты A1 — 0,1
$active_sheet->setCellValueByColumnAndRow(0, 1, ‘Сегодня ‘.date(‘d-m-Y’));
$active_sheet->setCellValue(‘A3’, ‘id’);
$active_sheet->setCellValue(‘B3’, ‘name’);
$active_sheet->setCellValue(‘C3’, ‘info’);

//Вставка данных из выборки
$start = 4;
$i = 0;
foreach($l as $row_l) setCellValueByColumnAndRow(0, $next, $row_l[‘id’]);
$active_sheet->setCellValueByColumnAndRow(1, $next, $row_l[‘name’]);
$active_sheet->setCellValueByColumnAndRow(2, $next, $row_l[‘info’]);

//Отправляем заголовки с типом контекста и именем файла
header(«Content-Type:application/vnd.ms-excel»);
header(«Content-Disposition:attachment;filename=’simple.xlsx’»);

//Сохраняем файл с помощью PHPExcel_IOFactory и указываем тип Excel
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, ‘Excel2007’);

//Отправляем файл
$objWriter->save(‘php://output’);
>;

if($_GET[‘do’]==2) getWorksheetIterator() as $worksheet)
getTitle();
//Последняя используемая строка
$lastRow = $worksheet->getHighestRow();
//Последний используемый столбец
$lastColumn = $worksheet->getHighestColumn();
//Последний используемый индекс столбца
$lastColumnIndex = PHPExcel_Cell::columnIndexFromString($lastColumn);

На этом — все, видео выложу на своем канале в YouTube

Источник

application/andrew-inset N/A Andrew Toolkit application/applixware .aw Applixware application/atom+xml .atom, .xml Atom Syndication Format application/atomcat+xml .atomcat Atom Publishing Protocol application/atomsvc+xml .atomsvc Atom Publishing Protocol Service Document application/ccxml+xml, .ccxml Voice Browser Call Control application/cdmi-capability .cdmia Cloud Data Management Interface (CDMI) — Capability application/cdmi-container .cdmic Cloud Data Management Interface (CDMI) — Contaimer application/cdmi-domain .cdmid Cloud Data Management Interface (CDMI) — Domain application/cdmi-object .cdmio Cloud Data Management Interface (CDMI) — Object application/cdmi-queue .cdmiq Cloud Data Management Interface (CDMI) — Queue application/cu-seeme .cu CU-SeeMe application/davmount+xml .davmount Web Distributed Authoring and Versioning application/dssc+der .dssc Data Structure for the Security Suitability of Cryptographic Algorithms application/dssc+xml .xdssc Data Structure for the Security Suitability of Cryptographic Algorithms application/ecmascript .es ECMAScript application/emma+xml .emma Extensible MultiModal Annotation application/epub+zip .epub Electronic Publication application/exi .exi Efficient XML Interchange application/font-tdpfr .pfr Portable Font Resource application/hyperstudio .stk Hyperstudio application/ipfix .ipfix Internet Protocol Flow Information Export application/java-archive .jar Java Archive application/java-serialized-object .ser Java Serialized Object application/java-vm .class Java Bytecode File application/javascript .js JavaScript application/json .json JavaScript Object Notation (JSON) application/mac-binhex40 .hqx Macintosh BinHex 4.0 application/mac-compactpro .cpt Compact Pro application/mads+xml .mads Metadata Authority Description Schema application/marc .mrc MARC Formats application/marcxml+xml .mrcx MARC21 XML Schema application/mathematica .ma Mathematica Notebooks application/mathml+xml .mathml Mathematical Markup Language application/mbox .mbox Mbox database files application/mediaservercontrol+xml .mscml Media Server Control Markup Language application/metalink4+xml .meta4 Metalink application/mets+xml .mets Metadata Encoding and Transmission Standard application/mods+xml .mods Metadata Object Description Schema application/mp21 .m21 MPEG-21 application/mp4 .mp4 MPEG4 application/msword .doc Microsoft Word application/mxf .mxf Material Exchange Format application/octet-stream .bin Binary Data application/oda .oda Office Document Architecture application/oebps-package+xml .opf Open eBook Publication Structure application/ogg .ogx Ogg application/onenote .onetoc Microsoft OneNote application/patch-ops-error+xml .xer XML Patch Framework application/pdf .pdf Adobe Portable Document Format application/pgp-encrypted .pgp Pretty Good Privacy application/pgp-signature .pgp Pretty Good Privacy — Signature application/pics-rules .prf PICSRules application/pkcs10 .p10 PKCS #10 — Certification Request Standard application/pkcs7-mime .p7m PKCS #7 — Cryptographic Message Syntax Standard application/pkcs7-signature .p7s PKCS #7 — Cryptographic Message Syntax Standard application/pkcs8 .p8 PKCS #8 — Private-Key Information Syntax Standard application/pkix-attr-cert .ac Attribute Certificate application/pkix-cert .cer Internet Public Key Infrastructure — Certificate application/pkix-crl .crl Internet Public Key Infrastructure — Certificate Revocation Lists application/pkix-pkipath .pkipath Internet Public Key Infrastructure — Certification Path application/pkixcmp .pki Internet Public Key Infrastructure — Certificate Management Protocole application/pls+xml .pls Pronunciation Lexicon Specification application/postscript .ai PostScript application/prs.cww .cww CU-Writer application/pskc+xml .pskcxml Portable Symmetric Key Container application/rdf+xml .rdf Resource Description Framework application/reginfo+xml .rif IMS Networks application/relax-ng-compact-syntax .rnc Relax NG Compact Syntax application/resource-lists-diff+xml .rld XML Resource Lists Diff application/resource-lists+xml .rl XML Resource Lists application/rls-services+xml .rs XML Resource Lists application/rsd+xml .rsd Really Simple Discovery application/rss+xml .rss, .xml RSS — Really Simple Syndication application/rtf .rtf Rich Text Format application/sbml+xml .sbml Systems Biology Markup Language application/scvp-cv-request .scq Server-Based Certificate Validation Protocol — Validation Request application/scvp-cv-response .scs Server-Based Certificate Validation Protocol — Validation Response application/scvp-vp-request .spq Server-Based Certificate Validation Protocol — Validation Policies — Request application/scvp-vp-response .spp Server-Based Certificate Validation Protocol — Validation Policies — Response application/sdp .sdp Session Description Protocol application/set-payment-initiation .setpay Secure Electronic Transaction — Payment application/set-registration-initiation .setreg Secure Electronic Transaction — Registration application/shf+xml .shf S Hexdump Format application/smil+xml .smi Synchronized Multimedia Integration Language application/sparql-query .rq SPARQL — Query application/sparql-results+xml .srx SPARQL — Results application/srgs .gram Speech Recognition Grammar Specification application/srgs+xml .grxml Speech Recognition Grammar Specification — XML application/sru+xml .sru Search/Retrieve via URL Response Format application/ssml+xml .ssml Speech Synthesis Markup Language application/tei+xml .tei Text Encoding and Interchange application/thraud+xml .tfi Sharing Transaction Fraud Data application/timestamped-data .tsd Time Stamped Data Envelope application/vnd.3gpp.pic-bw-large .plb 3rd Generation Partnership Project — Pic Large application/vnd.3gpp.pic-bw-small .psb 3rd Generation Partnership Project — Pic Small application/vnd.3gpp.pic-bw-var .pvb 3rd Generation Partnership Project — Pic Var application/vnd.3gpp2.tcap .tcap 3rd Generation Partnership Project — Transaction Capabilities Application Part application/vnd.3m.post-it-notes .pwn 3M Post It Notes application/vnd.accpac.simply.aso .aso Simply Accounting application/vnd.accpac.simply.imp .imp Simply Accounting — Data Import application/vnd.acucobol .acu ACU Cobol application/vnd.acucorp .atc ACU Cobol application/vnd.adobe.air-application-installer-package+zip .air Adobe AIR Application application/vnd.adobe.fxp .fxp Adobe Flex Project application/vnd.adobe.xdp+xml .xdp Adobe XML Data Package application/vnd.adobe.xfdf .xfdf Adobe XML Forms Data Format application/vnd.ahead.space .ahead Ahead AIR Application application/vnd.airzip.filesecure.azf .azf AirZip FileSECURE application/vnd.airzip.filesecure.azs .azs AirZip FileSECURE application/vnd.amazon.ebook .azw Amazon Kindle eBook format application/vnd.americandynamics.acc .acc Active Content Compression application/vnd.amiga.ami .ami AmigaDE application/vnd.android.package-archive .apk Android Package Archive application/vnd.anser-web-certificate-issue-initiation .cii ANSER-WEB Terminal Client — Certificate Issue application/vnd.anser-web-funds-transfer-initiation .fti ANSER-WEB Terminal Client — Web Funds Transfer application/vnd.antix.game-component .atx Antix Game Player application/vnd.apple.installer+xml .mpkg Apple Installer Package application/vnd.apple.mpegurl .m3u8 Multimedia Playlist Unicode application/vnd.aristanetworks.swi .swi Arista Networks Software Image application/vnd.audiograph .aep Audiograph application/vnd.blueice.multipass .mpm Blueice Research Multipass application/vnd.bmi .bmi BMI Drawing Data Interchange application/vnd.businessobjects .rep BusinessObjects application/vnd.chemdraw+xml .cdxml CambridgeSoft Chem Draw application/vnd.chipnuts.karaoke-mmd .mmd Karaoke on Chipnuts Chipsets application/vnd.cinderella .cdy Interactive Geometry Software Cinderella application/vnd.claymore .cla Claymore Data Files application/vnd.cloanto.rp9 .rp9 RetroPlatform Player application/vnd.clonk.c4group .c4g Clonk Game application/vnd.cluetrust.cartomobile-config .c11amc ClueTrust CartoMobile — Config application/vnd.cluetrust.cartomobile-config-pkg .c11amz ClueTrust CartoMobile — Config Package application/vnd.commonspace .csp Sixth Floor Media — CommonSpace application/vnd.contact.cmsg .cdbcmsg CIM Database application/vnd.cosmocaller .cmc CosmoCaller application/vnd.crick.clicker .clkx CrickSoftware — Clicker application/vnd.crick.clicker.keyboard .clkk CrickSoftware — Clicker — Keyboard application/vnd.crick.clicker.palette .clkp CrickSoftware — Clicker — Palette application/vnd.crick.clicker.template .clkt CrickSoftware — Clicker — Template application/vnd.crick.clicker.wordbank .clkw CrickSoftware — Clicker — Wordbank application/vnd.criticaltools.wbs+xml .wbs Critical Tools — PERT Chart EXPERT application/vnd.ctc-posml .pml PosML application/vnd.cups-ppd .ppd Adobe PostScript Printer Description File Format application/vnd.curl.car .car CURL Applet application/vnd.curl.pcurl .pcurl CURL Applet application/vnd.data-vision.rdz .rdz RemoteDocs R-Viewer application/vnd.denovo.fcselayout-link .fe_launch FCS Express Layout Link application/vnd.dna .dna New Moon Liftoff/DNA application/vnd.dolby.mlp .mlp Dolby Meridian Lossless Packing application/vnd.dpgraph .dpg DPGraph application/vnd.dreamfactory .dfac DreamFactory application/vnd.dvb.ait .ait Digital Video Broadcasting application/vnd.dvb.service .svc Digital Video Broadcasting application/vnd.dynageo .geo DynaGeo application/vnd.ecowin.chart .mag EcoWin Chart application/vnd.enliven .nml Enliven Viewer application/vnd.epson.esf .esf QUASS Stream Player application/vnd.epson.msf .msf QUASS Stream Player application/vnd.epson.quickanime .qam QuickAnime Player application/vnd.epson.salt .slt SimpleAnimeLite Player application/vnd.epson.ssf .ssf QUASS Stream Player application/vnd.eszigno3+xml .es3 MICROSEC e-Szign¢ application/vnd.ezpix-album .ez2 EZPix Secure Photo Album application/vnd.ezpix-package .ez3 EZPix Secure Photo Album application/vnd.fdf .fdf Forms Data Format application/vnd.fdsn.seed .seed Digital Siesmograph Networks — SEED Datafiles application/vnd.flographit .gph NpGraphIt application/vnd.fluxtime.clip .ftc FluxTime Clip application/vnd.framemaker .fm FrameMaker Normal Format application/vnd.frogans.fnc .fnc Frogans Player application/vnd.frogans.ltf .ltf Frogans Player application/vnd.fsc.weblaunch .fsc Friendly Software Corporation application/vnd.fujitsu.oasys .oas Fujitsu Oasys application/vnd.fujitsu.oasys2 .oa2 Fujitsu Oasys application/vnd.fujitsu.oasys3 .oa3 Fujitsu Oasys application/vnd.fujitsu.oasysgp .fg5 Fujitsu Oasys application/vnd.fujitsu.oasysprs .bh2 Fujitsu Oasys application/vnd.fujixerox.ddd .ddd Fujitsu — Xerox 2D CAD Data application/vnd.fujixerox.docuworks .xdw Fujitsu — Xerox DocuWorks application/vnd.fujixerox.docuworks.binder .xbd Fujitsu — Xerox DocuWorks Binder application/vnd.fuzzysheet .fzs FuzzySheet application/vnd.genomatix.tuxedo .txd Genomatix Tuxedo Framework application/vnd.geogebra.file .ggb GeoGebra application/vnd.geogebra.tool .ggt GeoGebra application/vnd.geometry-explorer .gex GeoMetry Explorer application/vnd.geonext .gxt GEONExT and JSXGraph application/vnd.geoplan .g2w GeoplanW application/vnd.geospace .g3w GeospacW application/vnd.gmx .gmx GameMaker ActiveX application/vnd.google-earth.kml+xml .kml Google Earth — KML application/vnd.google-earth.kmz .kmz Google Earth — Zipped KML application/vnd.grafeq .gqf GrafEq application/vnd.groove-account .gac Groove — Account application/vnd.groove-help .ghf Groove — Help application/vnd.groove-identity-message .gim Groove — Identity Message application/vnd.groove-injector .grv Groove — Injector application/vnd.groove-tool-message .gtm Groove — Tool Message application/vnd.groove-tool-template .tpl Groove — Tool Template application/vnd.groove-vcard .vcg Groove — Vcard application/vnd.hal+xml .hal Hypertext Application Language application/vnd.handheld-entertainment+xml .zmm ZVUE Media Manager application/vnd.hbci .hbci Homebanking Computer Interface (HBCI) application/vnd.hhe.lesson-player .les Archipelago Lesson Player application/vnd.hp-hpgl .hpgl HP-GL/2 and HP RTL application/vnd.hp-hpid .hpid Hewlett Packard Instant Delivery application/vnd.hp-hps .hps Hewlett-Packard’s WebPrintSmart application/vnd.hp-jlyt .jlt HP Indigo Digital Press — Job Layout Languate application/vnd.hp-pcl .pcl HP Printer Command Language application/vnd.hp-pclxl .pclxl PCL 6 Enhanced (Formely PCL XL) application/vnd.hydrostatix.sof-data .sfd-hdstx Hydrostatix Master Suite application/vnd.hzn-3d-crossword .x3d 3D Crossword Plugin application/vnd.ibm.minipay .mpy MiniPay application/vnd.ibm.modcap .afp MO:DCA-P application/vnd.ibm.rights-management .irm IBM DB2 Rights Manager application/vnd.ibm.secure-container .sc IBM Electronic Media Management System — Secure Container application/vnd.iccprofile .icc ICC profile application/vnd.igloader .igl igLoader application/vnd.immervision-ivp .ivp ImmerVision PURE Players application/vnd.immervision-ivu .ivu ImmerVision PURE Players application/vnd.insors.igm .igm IOCOM Visimeet application/vnd.intercon.formnet .xpw Intercon FormNet application/vnd.intergeo .i2g Interactive Geometry Software application/vnd.intu.qbo .qbo Open Financial Exchange application/vnd.intu.qfx .qfx Quicken application/vnd.ipunplugged.rcprofile .rcprofile IP Unplugged Roaming Client application/vnd.irepository.package+xml .irp iRepository / Lucidoc Editor application/vnd.is-xpr .xpr Express by Infoseek application/vnd.isac.fcs .fcs International Society for Advancement of Cytometry application/vnd.jam .jam Lightspeed Audio Lab application/vnd.jcp.javame.midlet-rms .rms Mobile Information Device Profile application/vnd.jisp .jisp RhymBox application/vnd.joost.joda-archive .joda Joda Archive application/vnd.kahootz .ktz Kahootz application/vnd.kde.karbon .karbon KDE KOffice Office Suite — Karbon application/vnd.kde.kchart .chrt KDE KOffice Office Suite — KChart application/vnd.kde.kformula .kfo KDE KOffice Office Suite — Kformula application/vnd.kde.kivio .flw KDE KOffice Office Suite — Kivio application/vnd.kde.kontour .kon KDE KOffice Office Suite — Kontour application/vnd.kde.kpresenter .kpr KDE KOffice Office Suite — Kpresenter application/vnd.kde.kspread .ksp KDE KOffice Office Suite — Kspread application/vnd.kde.kword .kwd KDE KOffice Office Suite — Kword application/vnd.kenameaapp .htke Kenamea App application/vnd.kidspiration .kia Kidspiration application/vnd.kinar .kne Kinar Applications application/vnd.koan .skp SSEYO Koan Play File application/vnd.kodak-descriptor .sse Kodak Storyshare application/vnd.las.las+xml .lasxml Laser App Enterprise application/vnd.llamagraphics.life-balance.desktop .lbd Life Balance — Desktop Edition application/vnd.llamagraphics.life-balance.exchange+xml .lbe Life Balance — Exchange Format application/vnd.lotus-1-2-3 0,123 Lotus 1-2-3 application/vnd.lotus-approach .apr Lotus Approach application/vnd.lotus-freelance .pre Lotus Freelance application/vnd.lotus-notes .nsf Lotus Notes application/vnd.lotus-organizer .org Lotus Organizer application/vnd.lotus-screencam .scm Lotus Screencam application/vnd.lotus-wordpro .lwp Lotus Wordpro application/vnd.macports.portpkg .portpkg MacPorts Port System application/vnd.mcd .mcd Micro CADAM Helix D&D application/vnd.medcalcdata .mc1 MedCalc application/vnd.mediastation.cdkey .cdkey MediaRemote application/vnd.mfer .mwf Medical Waveform Encoding Format application/vnd.mfmp .mfm Melody Format for Mobile Platform application/vnd.micrografx.flo .flo Micrografx application/vnd.micrografx.igx .igx Micrografx iGrafx Professional application/vnd.mif .mif FrameMaker Interchange Format application/vnd.mobius.daf .daf Mobius Management Systems — UniversalArchive application/vnd.mobius.dis .dis Mobius Management Systems — Distribution Database application/vnd.mobius.mbk .mbk Mobius Management Systems — Basket file application/vnd.mobius.mqy .mqy Mobius Management Systems — Query File application/vnd.mobius.msl .msl Mobius Management Systems — Script Language application/vnd.mobius.plc .plc Mobius Management Systems — Policy Definition Language File application/vnd.mobius.txf .txf Mobius Management Systems — Topic Index File application/vnd.mophun.application .mpn Mophun VM application/vnd.mophun.certificate .mpc Mophun Certificate application/vnd.mozilla.xul+xml .xul XUL — XML User Interface Language application/vnd.ms-artgalry .cil Microsoft Artgalry application/vnd.ms-cab-compressed .cab Microsoft Cabinet File application/vnd.ms-excel .xls Microsoft Excel application/vnd.ms-excel.addin.macroenabled.12 .xlam Microsoft Excel — Add-In File application/vnd.ms-excel.sheet.binary.macroenabled.12 .xlsb Microsoft Excel — Binary Workbook application/vnd.ms-excel.sheet.macroenabled.12 .xlsm Microsoft Excel — Macro-Enabled Workbook application/vnd.ms-excel.template.macroenabled.12 .xltm Microsoft Excel — Macro-Enabled Template File application/vnd.ms-fontobject .eot Microsoft Embedded OpenType application/vnd.ms-htmlhelp .chm Microsoft Html Help File application/vnd.ms-ims .ims Microsoft Class Server application/vnd.ms-lrm .lrm Microsoft Learning Resource Module application/vnd.ms-officetheme .thmx Microsoft Office System Release Theme application/vnd.ms-pki.seccat .cat Microsoft Trust UI Provider — Security Catalog application/vnd.ms-pki.stl .stl Microsoft Trust UI Provider — Certificate Trust Link application/vnd.ms-powerpoint .ppt Microsoft PowerPoint application/vnd.ms-powerpoint.addin.macroenabled.12 .ppam Microsoft PowerPoint — Add-in file application/vnd.ms-powerpoint.presentation.macroenabled.12 .pptm Microsoft PowerPoint — Macro-Enabled Presentation File application/vnd.ms-powerpoint.slide.macroenabled.12 .sldm Microsoft PowerPoint — Macro-Enabled Open XML Slide application/vnd.ms-powerpoint.slideshow.macroenabled.12 .ppsm Microsoft PowerPoint — Macro-Enabled Slide Show File application/vnd.ms-powerpoint.template.macroenabled.12 .potm Microsoft PowerPoint — Macro-Enabled Template File application/vnd.ms-project .mpp Microsoft Project application/vnd.ms-word.document.macroenabled.12 .docm Microsoft Word — Macro-Enabled Document application/vnd.ms-word.template.macroenabled.12 .dotm Microsoft Word — Macro-Enabled Template application/vnd.ms-works .wps Microsoft Works application/vnd.ms-wpl .wpl Microsoft Windows Media Player Playlist application/vnd.ms-xpsdocument .xps Microsoft XML Paper Specification application/vnd.mseq .mseq 3GPP MSEQ File application/vnd.musician .mus MUsical Score Interpreted Code Invented for the ASCII designation of Notation application/vnd.muvee.style .msty Muvee Automatic Video Editing application/vnd.neurolanguage.nlu .nlu neuroLanguage application/vnd.noblenet-directory .nnd NobleNet Directory application/vnd.noblenet-sealer .nns NobleNet Sealer application/vnd.noblenet-web .nnw NobleNet Web application/vnd.nokia.n-gage.data .ngdat N-Gage Game Data application/vnd.nokia.n-gage.symbian.install .n-gage N-Gage Game Installer application/vnd.nokia.radio-preset .rpst Nokia Radio Application — Preset application/vnd.nokia.radio-presets .rpss Nokia Radio Application — Preset application/vnd.novadigm.edm .edm Novadigm’s RADIA and EDM products application/vnd.novadigm.edx .edx Novadigm’s RADIA and EDM products application/vnd.novadigm.ext .ext Novadigm’s RADIA and EDM products application/vnd.oasis.opendocument.chart .odc OpenDocument Chart application/vnd.oasis.opendocument.chart-template .otc OpenDocument Chart Template application/vnd.oasis.opendocument.database .odb OpenDocument Database application/vnd.oasis.opendocument.formula .odf OpenDocument Formula application/vnd.oasis.opendocument.formula-template .odft OpenDocument Formula Template application/vnd.oasis.opendocument.graphics .odg OpenDocument Graphics application/vnd.oasis.opendocument.graphics-template .otg OpenDocument Graphics Template application/vnd.oasis.opendocument.image .odi OpenDocument Image application/vnd.oasis.opendocument.image-template .oti OpenDocument Image Template application/vnd.oasis.opendocument.presentation .odp OpenDocument Presentation application/vnd.oasis.opendocument.presentation-template .otp OpenDocument Presentation Template application/vnd.oasis.opendocument.spreadsheet .ods OpenDocument Spreadsheet application/vnd.oasis.opendocument.spreadsheet-template .ots OpenDocument Spreadsheet Template application/vnd.oasis.opendocument.text .odt OpenDocument Text application/vnd.oasis.opendocument.text-master .odm OpenDocument Text Master application/vnd.oasis.opendocument.text-template .ott OpenDocument Text Template application/vnd.oasis.opendocument.text-web .oth Open Document Text Web application/vnd.olpc-sugar .xo Sugar Linux Application Bundle application/vnd.oma.dd2+xml .dd2 OMA Download Agents application/vnd.openofficeorg.extension .oxt Open Office Extension application/vnd.openxmlformats-officedocument.presentationml.presentation .pptx Microsoft Office — OOXML — Presentation application/vnd.openxmlformats-officedocument.presentationml.slide .sldx Microsoft Office — OOXML — Presentation (Slide) application/vnd.openxmlformats-officedocument.presentationml.slideshow .ppsx Microsoft Office — OOXML — Presentation (Slideshow) application/vnd.openxmlformats-officedocument.presentationml.template .potx Microsoft Office — OOXML — Presentation Template application/vnd.openxmlformats-officedocument.spreadsheetml.sheet .xlsx Microsoft Office — OOXML — Spreadsheet application/vnd.openxmlformats-officedocument.spreadsheetml.template .xltx Microsoft Office — OOXML — Spreadsheet Template application/vnd.openxmlformats-officedocument.wordprocessingml.document .docx Microsoft Office — OOXML — Word Document application/vnd.openxmlformats-officedocument.wordprocessingml.template .dotx Microsoft Office — OOXML — Word Document Template application/vnd.osgeo.mapguide.package .mgp MapGuide DBXML application/vnd.osgi.dp .dp OSGi Deployment Package application/vnd.palm .pdb PalmOS Data application/vnd.pawaafile .paw PawaaFILE application/vnd.pg.format .str Proprietary P&G Standard Reporting System application/vnd.pg.osasli .ei6 Proprietary P&G Standard Reporting System application/vnd.picsel .efif Pcsel eFIF File application/vnd.pmi.widget .wg Qualcomm’s Plaza Mobile Internet application/vnd.pocketlearn .plf PocketLearn Viewers application/vnd.powerbuilder6 .pbd PowerBuilder application/vnd.previewsystems.box .box Preview Systems ZipLock/VBox application/vnd.proteus.magazine .mgz EFI Proteus application/vnd.publishare-delta-tree .qps PubliShare Objects application/vnd.pvi.ptid1 .ptid Princeton Video Image application/vnd.quark.quarkxpress .qxd QuarkXpress application/vnd.realvnc.bed .bed RealVNC application/vnd.recordare.musicxml .mxl Recordare Applications application/vnd.recordare.musicxml+xml .musicxml Recordare Applications application/vnd.rig.cryptonote .cryptonote CryptoNote application/vnd.rim.cod .cod Blackberry COD File application/vnd.rn-realmedia .rm RealMedia application/vnd.route66.link66+xml .link66 ROUTE 66 Location Based Services application/vnd.sailingtracker.track .st SailingTracker application/vnd.seemail .see SeeMail application/vnd.sema .sema Secured eMail application/vnd.semd .semd Secured eMail application/vnd.semf .semf Secured eMail application/vnd.shana.informed.formdata .ifm Shana Informed Filler application/vnd.shana.informed.formtemplate .itp Shana Informed Filler application/vnd.shana.informed.interchange .iif Shana Informed Filler application/vnd.shana.informed.package .ipk Shana Informed Filler application/vnd.simtech-mindmapper .twd SimTech MindMapper application/vnd.smaf .mmf SMAF File application/vnd.smart.teacher .teacher SMART Technologies Apps application/vnd.solent.sdkm+xml .sdkm SudokuMagic application/vnd.spotfire.dxp .dxp TIBCO Spotfire application/vnd.spotfire.sfs .sfs TIBCO Spotfire application/vnd.stardivision.calc .sdc StarOffice — Calc application/vnd.stardivision.draw .sda StarOffice — Draw application/vnd.stardivision.impress .sdd StarOffice — Impress application/vnd.stardivision.math .smf StarOffice — Math application/vnd.stardivision.writer .sdw StarOffice — Writer application/vnd.stardivision.writer-global .sgl StarOffice — Writer (Global) application/vnd.stepmania.stepchart .sm StepMania application/vnd.sun.xml.calc .sxc OpenOffice — Calc (Spreadsheet) application/vnd.sun.xml.calc.template .stc OpenOffice — Calc Template (Spreadsheet) application/vnd.sun.xml.draw .sxd OpenOffice — Draw (Graphics) application/vnd.sun.xml.draw.template .std OpenOffice — Draw Template (Graphics) application/vnd.sun.xml.impress .sxi OpenOffice — Impress (Presentation) application/vnd.sun.xml.impress.template .sti OpenOffice — Impress Template (Presentation) application/vnd.sun.xml.math .sxm OpenOffice — Math (Formula) application/vnd.sun.xml.writer .sxw OpenOffice — Writer (Text — HTML) application/vnd.sun.xml.writer.global .sxg OpenOffice — Writer (Text — HTML) application/vnd.sun.xml.writer.template .stw OpenOffice — Writer Template (Text — HTML) application/vnd.sus-calendar .sus ScheduleUs application/vnd.svd .svd SourceView Document application/vnd.symbian.install .sis Symbian Install Package application/vnd.syncml.dm+wbxml .bdm SyncML — Device Management application/vnd.syncml.dm+xml .xdm SyncML — Device Management application/vnd.syncml+xml .xsm SyncML application/vnd.tao.intent-module-archive .tao Tao Intent application/vnd.tmobile-livetv .tmo MobileTV application/vnd.trid.tpt .tpt TRI Systems Config application/vnd.triscape.mxs .mxs Triscape Map Explorer application/vnd.trueapp .tra True BASIC application/vnd.ufdl .ufd Universal Forms Description Language application/vnd.uiq.theme .utz User Interface Quartz — Theme (Symbian) application/vnd.umajin .umj UMAJIN application/vnd.unity .unityweb Unity 3d application/vnd.uoml+xml .uoml Unique Object Markup Language application/vnd.vcx .vcx VirtualCatalog application/vnd.visio .vsd Microsoft Visio application/vnd.visio2013 .vsdx Microsoft Visio 2013 application/vnd.visionary .vis Visionary application/vnd.vsf .vsf Viewport+ application/vnd.wap.wbxml .wbxml WAP Binary XML (WBXML) application/vnd.wap.wmlc .wmlc Compiled Wireless Markup Language (WMLC) application/vnd.wap.wmlscriptc .wmlsc WMLScript application/vnd.webturbo .wtb WebTurbo application/vnd.wolfram.player .nbp Mathematica Notebook Player application/vnd.wordperfect .wpd Wordperfect application/vnd.wqd .wqd SundaHus WQ application/vnd.wt.stf .stf Worldtalk application/vnd.xara .xar CorelXARA application/vnd.xfdl .xfdl Extensible Forms Description Language application/vnd.yamaha.hv-dic .hvd HV Voice Dictionary application/vnd.yamaha.hv-script .hvs HV Script application/vnd.yamaha.hv-voice .hvp HV Voice Parameter application/vnd.yamaha.openscoreformat .osf Open Score Format application/vnd.yamaha.openscoreformat.osfpvg+xml .osfpvg OSFPVG application/vnd.yamaha.smaf-audio .saf SMAF Audio application/vnd.yamaha.smaf-phrase .spf SMAF Phrase application/vnd.yellowriver-custom-menu .cmp CustomMenu application/vnd.zul .zir Z.U.L. Geometry application/vnd.zzazz.deck+xml .zaz Zzazz Deck application/voicexml+xml .vxml VoiceXML application/widget .wgt Widget Packaging and XML Configuration application/winhlp .hlp WinHelp application/wsdl+xml .wsdl WSDL — Web Services Description Language application/wspolicy+xml .wspolicy Web Services Policy application/x-7z-compressed .7z 7-Zip application/x-abiword .abw AbiWord application/x-ace-compressed .ace Ace Archive application/x-apple-diskimage .dmg Apple Disk Image application/x-authorware-bin .aab Adobe (Macropedia) Authorware — Binary File application/x-authorware-map .aam Adobe (Macropedia) Authorware — Map application/x-authorware-seg .aas Adobe (Macropedia) Authorware — Segment File application/x-bcpio .bcpio Binary CPIO Archive application/x-bittorrent .torrent BitTorrent application/x-bzip .bz Bzip Archive application/x-bzip2 .bz2 Bzip2 Archive application/x-cdlink .vcd Video CD application/x-chat .chat pIRCh application/x-chess-pgn .pgn Portable Game Notation (Chess Games) application/x-cpio .cpio CPIO Archive application/x-csh .csh C Shell Script application/x-debian-package .deb Debian Package application/x-director .dir Adobe Shockwave Player application/x-doom .wad Doom Video Game application/x-dtbncx+xml .ncx Navigation Control file for XML (for ePub) application/x-dtbook+xml .dtb Digital Talking Book application/x-dtbresource+xml .res Digital Talking Book — Resource File application/x-dvi .dvi Device Independent File Format (DVI) application/x-font-bdf .bdf Glyph Bitmap Distribution Format application/x-font-ghostscript .gsf Ghostscript Font application/x-font-linux-psf .psf PSF Fonts application/x-font-otf .otf OpenType Font File application/x-font-pcf .pcf Portable Compiled Format application/x-font-snf .snf Server Normal Format application/x-font-ttf .ttf TrueType Font application/x-font-type1 .pfa PostScript Fonts application/x-font-woff .woff Web Open Font Format application/x-futuresplash .spl FutureSplash Animator application/x-gnumeric .gnumeric Gnumeric application/x-gtar .gtar GNU Tar Files application/x-hdf .hdf Hierarchical Data Format application/x-java-jnlp-file .jnlp Java Network Launching Protocol application/x-latex .latex LaTeX application/x-mobipocket-ebook .prc Mobipocket application/x-ms-application .application Microsoft ClickOnce application/x-ms-wmd .wmd Microsoft Windows Media Player Download Package application/x-ms-wmz .wmz Microsoft Windows Media Player Skin Package application/x-ms-xbap .xbap Microsoft XAML Browser Application application/x-msaccess .mdb Microsoft Access application/x-msbinder .obd Microsoft Office Binder application/x-mscardfile .crd Microsoft Information Card application/x-msclip .clp Microsoft Clipboard Clip application/x-msdownload .exe Microsoft Application application/x-msmediaview .mvb Microsoft MediaView application/x-msmetafile .wmf Microsoft Windows Metafile application/x-msmoney .mny Microsoft Money application/x-mspublisher .pub Microsoft Publisher application/x-msschedule .scd Microsoft Schedule+ application/x-msterminal .trm Microsoft Windows Terminal Services application/x-mswrite .wri Microsoft Wordpad application/x-netcdf .nc Network Common Data Form (NetCDF) application/x-pkcs12 .p12 PKCS #12 — Personal Information Exchange Syntax Standard application/x-pkcs7-certificates .p7b PKCS #7 — Cryptographic Message Syntax Standard (Certificates) application/x-pkcs7-certreqresp .p7r PKCS #7 — Cryptographic Message Syntax Standard (Certificate Request Response) application/x-rar-compressed .rar RAR Archive application/x-sh .sh Bourne Shell Script application/x-shar .shar Shell Archive application/x-shockwave-flash .swf Adobe Flash application/x-silverlight-app .xap Microsoft Silverlight application/x-stuffit .sit Stuffit Archive application/x-stuffitx .sitx Stuffit Archive application/x-sv4cpio .sv4cpio System V Release 4 CPIO Archive application/x-sv4crc .sv4crc System V Release 4 CPIO Checksum Data application/x-tar .tar Tar File (Tape Archive) application/x-tcl .tcl Tcl Script application/x-tex .tex TeX application/x-tex-tfm .tfm TeX Font Metric application/x-texinfo .texinfo GNU Texinfo Document application/x-ustar .ustar Ustar (Uniform Standard Tape Archive) application/x-wais-source .src WAIS Source application/x-x509-ca-cert .der X.509 Certificate application/x-xfig .fig Xfig application/x-xpinstall .xpi XPInstall — Mozilla application/xcap-diff+xml .xdf XML Configuration Access Protocol — XCAP Diff application/xenc+xml .xenc XML Encryption Syntax and Processing application/xhtml+xml .xhtml XHTML — The Extensible HyperText Markup Language application/xml .xml XML — Extensible Markup Language application/xml-dtd .dtd Document Type Definition application/xop+xml .xop XML-Binary Optimized Packaging application/xslt+xml .xslt XML Transformations application/xspf+xml .xspf XSPF — XML Shareable Playlist Format application/xv+xml .mxml MXML application/yang .yang YANG Data Modeling Language application/yin+xml .yin YIN (YANG — XML) application/zip .zip Zip Archive

MS Excel имеет следующие наблюдаемые типы MIME:

  • application/vnd.ms-excel (официальный)
  • application/msexcel
  • application/x-msexcel
  • application/x-ms-excel
  • application/x-excel
  • application/x-dos_ms_excel
  • application/xls
  • application/x-xls
  • application/vnd.openxmlformats-officedocument.spreadsheetml.sheet (xlsx)

Есть ли какой-то один тип, который подойдет для всех версий? Если нет, нужно ли нам устанавливать response.setContentType() для каждого из этих типов пантомимы по отдельности?

Кроме того, мы используем потоковую передачу файлов в нашем приложении для отображения документа (а не только Excel — любого типа документа). При этом, как мы можем сохранить имя файла, если пользователь решает сохранить файл — в настоящее время имя сервлета, отображающего файл, отображается как имя по умолчанию.

7 ответов

Лучший ответ

Я считаю, что стандарт Тип MIME для файлов Excel: application/vnd.ms-excel.

Что касается названия документа, вы должны указать в ответе следующий заголовок:

header('Content-Disposition: attachment; filename="name_of_excel_file.xls"');


367

Callum Watkins
22 Фев 2020 в 04:46

21

В чем разница между application / msexcel и application / vnd.ms-excel?

 – 

7

Если вы хотите отображать документ в браузере (если поддерживается), Content-Disposition должен быть «встроенным». См. stackoverflow.com/questions/1395151/…

 – 

4

Вам следует избегать использования Content-Disposition в HTTP, это имеет соображения безопасности. Content-Disposition предназначен только для электронной почты. См. stackoverflow.com/questions/1012437 для получения дополнительной информации.

 – 

Обратите внимание, что для формата файла OpenXML Excel XLSX определен другой тип Mime, полный список см. По предоставленной ссылке.

 – 

Что такое "безопасная" альтернатива размещению контента? Перейдя по вашей ссылке, затем ссылка в этом ответе, а затем ссылка в этом документе приведет нас сюда: tools.ietf.org/html/rfc6266#section-4.3. Насколько я могу судить, проблема безопасности связана только с именами файлов, предоставленными пользователями - если они содержат нелатинские символы или символы, недопустимые в некоторых ОС. Все основные браузеры имеют защиту от этих проблем. Windows и Mac также устанавливают флаг для файла, указывающий, что он был получен из Интернета, и появляется предупреждение при попытке его открыть.

 – 

Просыпаясь здесь я вижу старую ветку, но я почувствовал побуждение добавить «новый» формат .xlsx.

Согласно http://filext.com/file-extension/XLSX расширением для .xlsx является application/vnd.openxmlformats-officedocument.spreadsheetml.sheet . Было бы неплохо включить его при проверке типов mime!


191

Dave Jarvis
19 Янв 2013 в 02:27

2

Это было то, что я искал, спасибо, необходимое для поддержки последнего формата, а также предыдущего.

 – 

Вы всегда должны использовать тип MIME ниже, если хотите обслуживать файл Excel в формате xlsx .

application/vnd.openxmlformats-officedocument.spreadsheetml.sheet 


50

Siva Kranthi Kumar
1 Ноя 2012 в 09:26

Я устанавливал тип MIME из кода .NET, как показано ниже -

File(generatedFileName, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")

Мое приложение генерирует Excel с использованием OpenXML SDK. Этот тип MIME работал -

vnd.openxmlformats-officedocument.spreadsheetml.sheet


8

Aleksei Matiushkin
23 Ноя 2016 в 14:05

Я использую EPPlus для создания файла Excel .xlsx (на основе формата OpenXML). Для отправки этого файла Excel в виде вложения в электронное письмо я использую следующий тип MIME, он отлично работает с файлом, созданным EPPlus, и правильно открывается в предварительном просмотре почтового клиента ms-outlook.

string mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
System.Net.Mime.ContentType contentType = null;
if (mimeType?.Length > 0)
{
    contentType = new System.Net.Mime.ContentType(mimeType);
}


2

Vishwajit G
1 Ноя 2018 в 14:25

Для тех, кто все еще сталкивается с этим после использования всех возможных типов MIME, перечисленных в вопросе:

Я обнаружил, что iMac также имеют тенденцию генерировать MIME-тип «text / xls» для файлов XLS Excel, надеюсь, это поможет.


0

be_es
25 Май 2016 в 21:58

Для .xls используйте следующий тип содержимого

application/vnd.ms-excel

Для версии Excel 2007 и выше формата файлов .xlsx

application/vnd.openxmlformats-officedocument.spreadsheetml.sheet


33

Dulith De Costa
6 Апр 2019 в 10:21

Понравилась статья? Поделить с друзьями:
  • Fijj in the correct word
  • Figure translated to word
  • Figurative use of a word
  • Figurative language word find
  • Fight gone bad word