Javascript открыть файл excel

Открываем файлы формата Open XML Excel в JavaScript

Для загрузки информации о торговых точках в наш логистический SaaS-сервис «Муравьиная логистика» из Excel я решил использовать web-браузер. Обычно проще загрузить файл на сервер и с помощью любой библиотеки залить в БД. Но мне было интересно загрузить его построчно для контроля целостности каждой строки на клиенте, ну и, конечно, опробовать так всеми рекламируемое HTML5 FileAPI и Drag and Drop.

Книга Exсel – это ZIP архив с каталогами и файлами XML в формате Open XML. Парсить XML отлично умеет jQuery, а вот зиппить нет. Для этого на просторах сети была найдена библиотека zip.js, которая прекрасно справилась с поставленной задачей.

Итак, попробуем посмотреть, что же находится внутри архива:

var c = document.getElementById("comps"), FileDragHover = function (e) < e.stopPropagation(); e.preventDefault(); if(e.target.id==='comps') e.target.className = (e.type == "dragover" ? "filedrag hover" : "filedrag"); else c.className = (e.type == "dragover" ? "filedrag hover" : "filedrag"); >c.addEventListener("drop", function(e) < e.preventDefault(); c.className = "filedrag"; var files = e.target.files || e.dataTransfer.files; for (var i = 0, f; f = files[i]; i++) < if(f.name.toLowerCase().indexOf('xlsx')<=0) < alert('Это не файл Excel'); >else < zip.createReader(new zip.BlobReader(f), function(reader) < // Получаем все файлы архива reader.getEntries(function(entries) < // В консоли появятся все внутренности архива Excel console.info(entries) return false; >); >, function(error) < alert("Ошибка: " + error) >); > > return false; >, false); c.addEventListener("dragover", FileDragHover, false); c.addEventListener("dragleave", FileDragHover, false); 

Результат можно посмотреть тут. Скачайте пример файла и перетащите его на форму.
В консоли появится список всех файлов архива книги Excel. Среди свойств объектов, появившихся в консоли, есть filename, по нему-то мы и будем искать необходимые нам файлы XML.

Читайте также:  Css display type hidden

Отфильтруем только нужные для нас файлы:

// Получаем все файлы архива reader.getEntries(function(entries) < var a=[],st; for(var i in entries)< var e=entries[i]; var fn=e.filename.toLowerCase(); if(fn.indexOf("sheet")>0) < a.push(e); >else if(fn.indexOf("sharedstring")>0) < st=e; >> // Массив всех листов книги Excel console.info(a) // Ассоциативный массив строк console.info(st) return false; >); 

Результат можно посмотреть тут, закинув файл и посмотрев в консоль.

Далее нам необходимо извлечь данные простыми селекторами, для словаря строк это — st t, для записей таблицы с данными на листе это — sheetdata row.

Добавим функцию для вывода данных из листа Excel:

printExcelData = function(sheets, strings) < var unzipProgress = document.getElementById("progress"); unzipProgress.style.display='block'; strings.getData(new zip.TextWriter(), function(text) < // Получаем все строки листа для ассоциации с их кодами var i,st=$($.parseXML(decodeURIComponent(escape(text)))).find('si t'); for(i=0;i; for(i=0;i if(h) < d.push(o) >else h=o; >); var id_name=""; for(i in h) if(h[i]=='Comp_Id') < id_name=h[i]; break; >// Если поле Comp_Id есть в записи, значит лист наш if(id_name=='Comp_Id') < unzipProgress.style.display='none'; // Это заголовок таблицы данных s=""; for(i=0;i'; $('.result thead tr').append(s) // Это данные s=""; for(j=0; j'; for(i=0; i'+d[j][h[i]].toString()+''; > s+=''; > $('.result tbody').append(s) sheets=[]; return; > if(sheets.length>0) parseSheet(sheets.pop()); >, function(current, total) < unzipProgress.value = current; unzipProgress.max = total; >); > parseSheet(sheets.pop()); >, function(current, total) < unzipProgress.value = current; unzipProgress.max = total; >); > 

Так как Chrome считает преступлением использование HTML File API в кросс-домене (Uncaught SecurityError: An attempt was made to break through the security policy of the user agent.), последний пример выложил на Web-сервер.
Перетаскиваем файл и получаем стандартную таблицу HTML.

P.S.
Да, сейчас, как оказалось, есть Open XML SDK for JavaScript, но это тема для отдельной статьи…

Источник

Read Excel file using Javascript (XLSX or XLS)

In the previous post, I have explained how we can read csv file using javascript and HTML 5 filereader, now in this post, I have explained how we can use external library like xlsx to parse or read excel file using javascript and show it’s contents in HTML table. When file is uploaded using Javascript, it is read as Binary string initially, and then binary data is read using xlsx plugin.

Read XLSX using Javascript

Let’s beging by adding simple HTML file input and button to upload file

I have also included empty HTML div to create table inside it from our Excel file.

Now, we will create the function to upload the file and process the Excel file to get data from it and convert it into HTML table.

   
  1. UploadProcess: Uploads the file on button click and convert it into Binary data, it also check if Browser is IE then process accordingly to convert file into binary.
  2. ProcessExcel: this function takes the binary data, reads the Sheet name, create Table element and append each row in it.

I have explained lines of code using Comment.

Suppose our sample Excel file looks like this

So, if use the above code in HTML/Javascript, output will be as below

Read XLS file using Javascript

In a Similar way, we can read .xls (excel) file also and show it in HTML table, I will repeat the same code, just few lines of code is different, also we will be using different plugin in it which is for .xls

   
  1. We included difference JS plugin file :
  2. Changed a few lines of code for the function «GetTableFromExcel»

 //Read the Excel File data in binary var cfb = XLS.CFB.read(data, ); var workbook = XLS.parse_xlscfb(cfb); //get the name of First Sheet. var Sheet = workbook.SheetNames[0]; //Read all rows from First Sheet into an JSON array. var excelRows = XLS.utils.sheet_to_row_object_array(workbook.Sheets[Sheet]);?

The rest of the code remains the same.

Note: You need to pass .xls file in this code to make it work.

Convert Excel to JSON using Javascript

You can also upload excel and then convert it to JSON data and proceed with it further.

     

Here is the fiddle: https://jsfiddle.net/aszchkr0/ using which you can test the above code, just to search excel file and once value is changed you will find JSON result in textarea.

In the above code, we are reading excel using XLSX plugin, then we loop through each sheet and get XL row object and further convert it to JSON.

Источник

Оцените статью