Xls converting to linux

5 Methods to Convert xlsx Format Files to CSV on Linux CLI

XLSX is a file extension for an open XML spreadsheet file format used by Microsoft excel. Converting Microsoft Excel sheet to a Comma Separated file (CSV) is relatively very easy while using command line. The situation may arrive when you have a XLS file and you need to fill the database from it after formatting the data. It exists some methods in command line in order to do the conversion of the different format files.

1) Gnumeric spreadsheet program

Gnumeric is a spreadsheet program for Unix and Unix-like operating systems distributed under the GNU General Public License. It stores its information by creating files and re-opening these files during a future session. It can import and export spreadsheet data to and from multiple formats, including CSV, Microsoft Excel, HTML, OpenDocument, Quattro Pro, and LaTex.

Gnumeric is not present by default in the repository of your centos 7, you must first install the latest lux-release. First download it

Now you can install the lux release

With the lux-release installed, we can now install gnumeric via package

Now you can use the ssconvert command of the gnumeric spreadsheet to convert the file

You can visualize the file now

2) xlsx2csv converter

xlsx2csv converter is a python application that is capable to convert a batch of XLSX/XLS files to CSV format. You can specify exactly which sheets to be converted. If you have multiple sheets, the xlsx2csv give the possibility to export all the sheets at once, or one at a time.

To install it, you need to have python already installed. Then, you can proceed as below:

Now you can convert you xlsx file

You can check the content of the file

By default, the xlsx2csv command convert only the first sheet even if your file contains multiples sheets. Fortunately, it offes the possibilty to convert all the sheets or to choose the one to convert. You can use some interesting paramaters:

  • -a, —all to export all sheets
  • -d DELIMITER for columns delimiter in csv
  • -p SHEETDELIMITER for sheet delimiter used to separate sheets, pass » if you do not need delimiter, or ‘x07’ or ‘\f’ for form feed (default: ‘———‘)
  • -s SHEETID for the sheet number to convert

For example, if you want to convert only a specific sheet

Now if you want to convert all the sheet, you can do as below

You can check the content as below

You can see that the default delimiter helps to know the sheets.

3) csvkit tool

csvkit is a python library optimized for working with CSV files. It is a nice tool to manipulate, organize, analyze and work with data, using the csv format. It is very light and fast. It is used through the terminal with its in2csv command which converts a variety of common file formats, including xls, xlsx and fixed-width into CSV format..

Now you can convert as below:

4) unoconv

OpenOffice comes with the unoconv program to perform format conversions on the command line. It is present by default if openoffice is installed. You can use the manual

Читайте также:  Hidden city поиск скрытых предметов windows 10

The command is capable to convert between various file formats. by default, it converts in pdf. It means that you should indicate the desired format if you don’t want to have a undesired format. So, to convert in csv with the unoconv command, you need to use two main parameters:

  • -f which indicates the request the final format of the output file
  • -o to indicate the name and the path of the converted file

You can check the content

Note that the second row of our original xlsx file is empty, that is why you have the comma on the second line of the csv file.

5) Libreoffice headless

By starting the LibreOffice software from the command line you can assign various parameters, with which you can influence the performance. It is possible through the headless mode which help you to launch LibreOffice in command line without any graphical interface component. It gives you the possibility to convert file in some formats as you need. So, you can use it to convert xlsx files in csv. You need to use the indicated the final format (csv) with the —convert-to parameter followed by the file to convert as below:

Now you can check the file

You can directly convert some xlsx files as below:

You can look the converted as below

You can check the content of one file

We have seen the different tools available on Linux to convert any xlsx file format in csv file on command line. You can decide to convert the file in odt or pdf and it is possible with unoconv and libreoffice headless. Worth trying Miller tool which does conversion between formats and more.

Источник

Конвертируйте xlsx в csv в Linux с помощью командной строки

Я ищу способ конвертировать xlsx файлы в csv файлы в Linux.

Я не хочу использовать PHP / Perl или что-то подобное, так как я смотрю на обработку нескольких миллионов строк, поэтому мне нужно что-то быстрое. Я нашел программу в репозиториях Ubuntu под названием xls2csv, но она будет конвертировать только файлы xls (Office 2003) (которые я сейчас использую), но мне нужна поддержка более новых файлов Excel.

Приложение электронных таблиц Gnumeric поставляется с утилитой командной строки под названием ssconvert, которая может конвертировать различные форматы электронных таблиц:

Чтобы установить на Ubuntu:

Чтобы установить на Mac:

Вы можете сделать это с LibreOffice:

По неясным для меня причинам вам может потребоваться запустить это с помощью sudo. Вы можете заставить LibreOffice работать с sudo, не запрашивая пароль, добавив следующую строку в файл sudoers:

Если у вас уже есть среда рабочего стола, то я уверен, что Gnumeric / LibreOffice будет работать хорошо, но на автономном сервере (таком как Amazon Web Services) им требуются десятки зависимостей, которые также необходимо установить.

Я нашел эту альтернативу Python:

Потребовалось 2 секунды для установки и работает как шарм.

Если у вас есть несколько листов, вы можете экспортировать все сразу или по одному:

Он также ссылается на несколько альтернатив, встроенных в Bash, Python, Ruby и Java.

В bash я использовал эту команду libreoffice для преобразования всех моих файлов xlsx в текущем каталоге:

Он заботится о пробелах в имени файла.

Попробовал еще несколько лет спустя, и это не сработало. Этот поток дает несколько советов, но самым быстрым решением было запустить от имени пользователя root (или запустить sudo libreoffice ). Не элегантно, но быстро.

Используйте команду scalc.exe в Windows

Для деталей проверьте их отличные документы

Другой вариант — для удобства использовать R с помощью небольшой оболочки bash:

Если в .xlsx файле много листов, -s можно использовать флаг, чтобы получить нужный лист. Например:

second_sheet.csv будет содержать данные 2-го листа в my_file.xlsx .

Использовать приложение Gnumeric для работы с электронными таблицами, в котором утилита командной строки под названием ssconvert действительно очень просто:

Если вы можете запустить командную строку Java, вы можете сделать это с помощью Apache POI HSSF Excel Extractor . У него есть main метод, который говорит, что это экстрактор командной строки . Этот, кажется, просто вываливает все. Они указывают на этот пример, который конвертируется в CSV . Вам придется скомпилировать его, прежде чем вы сможете запустить его, но он тоже имеет main метод, поэтому вам не нужно делать много кода как такового, чтобы заставить его работать.

Читайте также:  Как архивировать файлы для linux

Другой вариант, который может сработать, но потребует некоторой работы на другом конце, состоит в том, чтобы заставить ваши файлы Excel поступать к вам в виде XML-данных Excel или электронной таблицы XML любого вызова MS, который форматирует в эти дни. Это откроет вам новый мир возможностей нарезать и нарезать кубиками так, как вы хотите.

Как говорили другие, libreoffice может конвертировать файлы xls в csv. Проблемой для меня был выбор листа.

Этот скрипт Python libreoffice отлично справляется с конвертацией одного листа в CSV.

Единственным недостатком (с моей стороны) является то, что —headless , похоже, не работает. У меня есть окно LO, которое появляется на секунду, а затем выходит.
Это нормально для меня, это единственный инструмент, который делает работу быстро.

Источник

How to convert xls file to csv file in Linux and vice versa

Excel is an Microsoft spreadsheet program and its extension is .xls or .xlsx. Now we as Linux user can convert xls file to csv file in Linux and .xls to .csv. This quick guide will help you how we can convert xls file to csv file in Linux using program called SSConvert and Unoconv.

Convert xls file to csv file in Linux.

1. Installing SSConvert to convert xls file to csv file in Linux

For REDHAT ,CENTOS and FEDORA.

For UBUNTU and DEBIAN.

Now to show demo on how to convert xls file to csv file in Linux. I am creating sample csv file as below:

So Firstly we will convert this file to xls.

In case you need xlsx file extension use below command:

You can also reconfirm file type using the file command as below:

Now lets convert this xls back to new csv file.

Even you can change the delimiter other than comma if you want. So lets take “;” as delimiter.

2. Installing unoconv program to convert xls file to csv file in Linux

For REDHAT ,CENTOS and FEDORA.

For UBUNTU and DEBIAN.

For showing demo to convert xls file to csv file in Linux we will be renaming our old example file as example1.csv.

Now lets convert this “example1.csv” to xls file.

This will create new “example1.xls” file in the same directory. In case you want to convert to xlsx format command would be:

Now lets convert xls file to csv file in Linux.

Now lets check the file type of the generated files:

Источник

Конвертировать xls в pdf на Linux

Появилась задача конвертировать xls в pdf на старом сервере с Linux, и это требование создало серьезные проблемы, потому что совершенно непонятно, как же это лучше сделать.

Для python есть разные утилиты pyPDF2 pyXLSX, но непонятно, как их «скрестить». Потому что все примеры того же pyPDF2 работают только с другими pdf или с рисованием на Canvas.

Для C++ я аналогично пока не нашел подходящего решения.

Ситуация усложняется еще тем, что исходный xls не тривиальный, с разными цветами и таблицами. Поэтому вариант перевода в csv, как промежуточный формат, например, отпадает. При этом не хотелось бы и переводить в jpg, потому что потом по тексту в pdf нужен будет поиск + проблемы с печатью.

При этом исходный xls состоит из множества worksheets, каждый из которых содержит таблицу. И многие таблицы шире, чем ширина листа в pdf. Соответственно, при переводе (я тестировал под windows) pdf эти таблицы некрасиво обрезает и огрызками вставляет, делая документ нечитабельным. Поэтому, ко всему прочему, worksheets в xls надо еще и уменьшать перед конвертацией так, чтобы в ширину она помещалась на одну страницу.

Смотрю в сторону unoconv и LibreOffice сейчас, но учитывая, что перед конвертацией надо делать еще манипуляции с xls, не представляю, как в результате решу.

Читайте также:  Acer install windows from usb

Еще есть вариант просто поднять там виртуалку с Windows с простеньким сервисом, который будет слушать сеть и выполнять эти действия. Но это решение выглядит большим костылем.

Решали ли вы уже такую задачу? Если да, то как? Может быть, есть какие-то идеи? Привязка к питону и C++ не обязательна.

Источник

Convert xlsx to csv in Linux with command line

I’m looking for a way to convert xlsx files to csv files on Linux.

I do not want to use PHP/Perl or anything like that since I’m looking at processing several millions of lines, so I need something quick. I found a program on the Ubuntu repos called xls2csv but it will only convert xls (Office 2003) files (which I’m currently using) but I need support for the newer Excel files.

10 Answers 10

The Gnumeric spreadsheet application comes with a command line utility called ssconvert that can convert between a variety of spreadsheet formats:

To install on Ubuntu:

To install on Mac:

You can do this with LibreOffice:

For reasons not clear to me, you might need to run this with sudo. You can make LibreOffice work with sudo without requiring a password by adding this line to you sudoers file:

If you already have a Desktop environment then I’m sure Gnumeric / LibreOffice would work well, but on a headless server (such as Amazon Web Services), they require dozens of dependencies that you also need to install.

I found this Python alternative:

Took 2 seconds to install and works like a charm.

If you have multiple sheets you can export all at once, or one at a time:

He also links to several alternatives built in Bash, Python, Ruby, and Java.

In bash, I used this libreoffice command to convert all my xlsx files in the current directory:

Close all your Libre Office open instances before executing, or it will fail silently.

The command takes care of spaces in the filename.

Tried again some years later, and it didn’t work. This thread gives some tips, but the quickest solution was to run as root (or running a sudo libreoffice ). Not elegant, but quick.

Use the command scalc.exe in Windows

For details check their excellent docs

Another option would be to use R via a small bash wrapper for convenience:

If .xlsx file has many sheets, -s flag can be used to get the sheet you want. For example:

second_sheet.csv would contain data of 2nd sheet in my_file.xlsx .

Using the Gnumeric spreadsheet application which comes which a commandline utility called ssconvert is indeed super simple:

If you are OK to run Java command line then you can do it with Apache POI HSSF’s Excel Extractor. It has a main method that says to be the command line extractor. This one seems to just dump everything out. They point out to this example that converts to CSV. You would have to compile it before you can run it but it too has a main method so you should not have to do much coding per se to make it work.

Another option that might fly but will require some work on the other end is to make your Excel files come to you as Excel XML Data or XML Spreadsheet of whatever MS calls that format these days. It will open a whole new world of opportunities for you to slice and dice it the way you want.

As others said, libreoffice can convert xls files to csv. The problem for me was the sheet selection.

This libreoffice Python script does a fine job at converting a single sheet to CSV.

The only downside (on my end) is that —headless doesn’t seem to work. I have a LO window that shows up for a second and then quits.
That’s OK with me, it’s the only tool that does the job rapidly.

Источник

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