Excel 2007 content type

How can I set the correct MIME type that works with excel 2007?
right now I have this:

header("Content-type: application/vnd.ms-excel; charset=UTF-8");

my browser keeps telling me that is a 97 2003 file, but when I try to open the file with excel 2007, the program shows some warning, I can see the document, but I’m trying to avoid that warning.

  • excel
  • types
  • header
  • mime

asked Oct 29, 2012 at 14:46

Camilo Salas's user avatar

4

  • Are you sending an actual Excel file, or a HTML table posing as an Excel file? Office 2007+ has «extension hardening» which makes sure the content of the file actually matches what it’s saying it is… blogs.msdn.com/b/vsofficedeveloper/archive/2008/03/11/…

    Oct 29, 2012 at 16:53

  • I think that is my problem. I have a php file that contains header info and one html table that contains the info thatI want to send to excel 2007. The link that you pointed shows the XML BIFF8, now I’m checking info about that.

    Oct 29, 2012 at 17:26

  • Some idea? i can’t figure it out how to do it..

    Oct 29, 2012 at 18:06

  • If extension hardening is set to the option which prevents anything other than an actual Excel file from opening, then you have to output the expected format. I’m not familiar enough with php to ffer any suggestions there.

    Oct 29, 2012 at 18:16

1 Answer

answered Oct 29, 2012 at 15:28

Jüri Ruut's user avatar

Jüri RuutJüri Ruut

2,49017 silver badges20 bronze badges

5

  • I try with that definition but I’m having troubles with the extension of the file.. Now I trying with xlsx but doesn’t work eathier.

    Oct 29, 2012 at 15:45

  • Is the document definitely an OfficeOpenXML file? What «warning» are you getting?

    Oct 29, 2012 at 16:17

  • and the extension of file to «.xlsx» in order to work with excel 2007 but… when I download the file and then try to open it, i get a message from ms excel tells me that can’t open the file becouse the format or the extension aren’t accepted.

    Oct 29, 2012 at 16:29

  • Works for me. @CamiloSalas you should mark this as an answer if it worked.

    Apr 23, 2015 at 14:36

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

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

Источник

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

This is a list of the MIME Types of all well known and lesser known file formats and kinds of documents from the Microsoft Office family.

You can find the MIME Types in the table ordered by the corresponding application Microsoft Word, Excel, Power Point and Access as well as the extension of the file.

Microsoft Word

Extension MIME-Type
DOC application/msword
DOCX application/vnd.openxmlformats-officedocument.wordprocessingml.document
DOT application/msword
DOTX application/vnd.openxmlformats-officedocument.wordprocessingml.template
DOCM application/vnd.ms-word.document.macroEnabled.12
DOTM application/vnd.ms-word.template.macroEnabled.12
DOCM application/vnd.ms-word.document.macroEnabled.12
DOTM application/vnd.ms-word.template.macroEnabled.12
WORD application/msword
W6W application/msword

Microsoft Excel

Extension MIME-Type
XLS application/msexcel
XLSX application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
XLT application/msexcel
XLTX application/vnd.openxmlformats-officedocument.spreadsheetml.template
XLA application/msexcel
XLW application/msexcel
XLSM application/vnd.ms-excel.sheet.macroEnabled.12
XLSB application/vnd.ms-excel.sheet.binary.macroEnabled.12
XLTM application/vnd.ms-excel.template.macroEnabled.12
XLAM application/vnd.ms-excel.addin.macroEnabled.12

Microsoft PowerPoint

Extension MIME-Type
PPT application/mspowerpoint
PPTX application/vnd.openxmlformats-officedocument.presentationml.presentation
POT application/mspowerpoint
POTX application/vnd.openxmlformats-officedocument.presentationml.template
PPS application/mspowerpoint
PPSX application/vnd.openxmlformats-officedocument.presentationml.slideshow
PPA application/mspowerpoint
PPAM application/vnd.ms-powerpoint.addin.macroEnabled.12
PPTM application/vnd.ms-powerpoint.presentation.macroEnabled.12
PPSM application/vnd.ms-powerpoint.slideshow.macroEnabled.12
POTM application/vnd.ms-powerpoint.template.macroEnabled.12

Microsoft Access

Extension MIME-Type
MDB application/msaccess
ACCDA application/msaccess
ACCDB application/msaccess
ACCDE application/msaccess
ACCDR application/msaccess
ACCDT application/msaccess
ADE application/msaccess
ADP application/msaccess
ADN application/msaccess
MDE application/msaccess
MDF application/msaccess
MDN application/msaccess
MDT application/msaccess
MDW application/msaccess

Other

Extension MIME-Type
CALCX application/vnd.ms-office.calx
HLP (Microsoft Windows Help) application/x-winhelp
MPP (Microsoft Project) application/msproject
THMX application/vnd.ms-officetheme
WRI (Microsoft Write) application/mswrite

I hope, I could help you with this list. If I should have forgotten something, just write a comment.

This article describes MIME Types and the corresponding file extension of the Microsoft Office documents. It will very be useful for document analysis, and you can easily define ContentType for the Microsoft Office associated documents in ASP.NET applications. Also you can use this details to customize MIME types in IIS server configuration.

 For Microsoft Office Excel, you can define content type like this example.
 Aspx page
<%response.ContentType=“application/vnd.ms-excel”%>

 C#
  Response.ContentType = “application/vnd.ms-excel”;

The following table lists the MIME types and file extensions that are associated  with the Microsoft Office documents.

Extension MIME Type
.doc application/msword
.dot application/msword
.docx application/vnd.openxmlformats-officedocument.wordprocessingml.document
.dotx application/vnd.openxmlformats-officedocument.wordprocessingml.template
.docm application/vnd.ms-word.document.macroEnabled.12
.dotm application/vnd.ms-word.template.macroEnabled.12
.xls application/vnd.ms-excel
.xlt application/vnd.ms-excel
.xla application/vnd.ms-excel
.xlsx application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
.xltx application/vnd.openxmlformats-officedocument.spreadsheetml.template
.xlsm application/vnd.ms-excel.sheet.macroEnabled.12
.xltm application/vnd.ms-excel.template.macroEnabled.12
.xlam application/vnd.ms-excel.addin.macroEnabled.12
.xlsb application/vnd.ms-excel.sheet.binary.macroEnabled.12
.ppt application/vnd.ms-powerpoint
.pot application/vnd.ms-powerpoint
.pps application/vnd.ms-powerpoint
.ppa application/vnd.ms-powerpoint
.pptx application/vnd.openxmlformats-officedocument.presentationml.presentation
.potx application/vnd.openxmlformats-officedocument.presentationml.template
.ppsx application/vnd.openxmlformats-officedocument.presentationml.slideshow
.ppam application/vnd.ms-powerpoint.addin.macroEnabled.12
.pptm application/vnd.ms-powerpoint.presentation.macroEnabled.12
.potm application/vnd.ms-powerpoint.template.macroEnabled.12
.ppsm application/vnd.ms-powerpoint.slideshow.macroEnabled.12

Thanks,
Morgan
Software Developer

The content type for .xlsx files is:

application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

Or use 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/application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

Response.AppendHeader("content-disposition", "attachment; filename=myfile.xlsx");

Or if you are trying to read the file then try this:

DataSet objds = new DataSet();
string ConnStr = "";
if (FileExtension == ".xlsx")
{
    ConnStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FileName + ";Extended Properties="Excel 12.0 Xml;HDR=No;IMEX=1";";
}
else
{
    ConnStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + FileName + ";Extended Properties="Excel 8.0;HDR=No;IMEX=1";";

}
OleDbCommand selectCommand = new OleDbCommand();
OleDbConnection connection = new OleDbConnection();
OleDbDataAdapter adapter = new OleDbDataAdapter();
connection.ConnectionString = ConnStr;
string strSQL = "SELECT * FROM [Sheet1$]";
if (connection.State != ConnectionState.Open)
    connection.Open();
OleDbCommand cmd = new OleDbCommand(strSQL, connection);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(objds);
connection.Close();

All the best.
—Amit

User-1668203914 posted

Hi,

Currently all our excel sheets are being generated in Excel (1997-2003) format which is of extension .xls. These types of excel will have a problem when user have higher version of office installed. (Due to Extension Hardening Feature : A warning messages
will be dispalyed before opening the excel sheet). As per our requirment we need to generate excel sheets in .xlsx format.

Code :

Case «EXCEL»       

                                Response.AppendHeader(«Content-Disposition»,»filename=» test&».xlsx»)                                 
                               
Response.ContentType = «application/vnd.openxmlformats-officedocument.spreadsheetml.sheet»

I have used the correct MIME type for Excel 2007/2010 as mentioned above.

Excel file which is being generated from web site is opening in .xlsx type but i am getting below error message :

Excel cannot open the file .xlsx because the file format or file extension is not valid.Please make sure that fiel is not corrupted. 

But when I tried to save the same file in .xls format, it is opening fine without any issues.

My web site is hosted in IIS 7, so b ydefault all MIME types are already added.

Can any one please help me in resolving the issue.

Thanks,

Naresh

Понравилась статья? Поделить с друзьями:
  • Excel 2003 имя формула
  • Excel 2003 стиль ячеек в
  • Excel 2003 или excel 2010
  • Excel 2003 стиль ссылок
  • Excel 2003 значение ячейки