0

Is there a way to copy the range of cells from Microsoft excel csv to the other cells in same file like with normal .xlsx file, or to the new .xlsx file?

Alternative to this is to simply save this file in .xlsx format, but i'm having problems with this method also due to UTF-16 LE coding.

Luka Herc
  • 11
  • 1
  • 4
  • 1
    The question is unclear - There's no `Excel CSV` file. CSV files are *nothing* more than flat text files with specific delimiters. `xlsx` files on the other hand are a completely different format, a ZIP package containing XML files using UTF8. Since CSV files are simply *text* files, you need to know their encoding in advance to read them properly. If you use the *wrong* encoding, you'll get garbage and likely lose data. You can't fix that in code. If the text file starts with a BOM, most libraries will be able to recognize it – Panagiotis Kanavos Jan 14 '20 at 11:26
  • I suspect what you need is a library that can read CSV files and one for XLSX files, like [openpyxl](https://openpyxl.readthedocs.io/en/stable/) and [csv](https://docs.python.org/3/library/csv.html). `csv` uses `open` and by default, the system's encoding. If that doesn't match your file, you should pass the `encoding` parameter to `open`, eg `encoding='utf-8'`. – Panagiotis Kanavos Jan 14 '20 at 11:29
  • Does this answer your question? [openpyxl convert CSV to EXCEL](https://stackoverflow.com/questions/12976378/openpyxl-convert-csv-to-excel) – Panagiotis Kanavos Jan 14 '20 at 11:29

1 Answers1

0

There are no Excel CSV files. CSV is a flat text file with a specific, minimal format. xlsx files on the other hand are ZIP packages containing XML files. I suspect what you really ask is how to read a CSV text file saved with one encoding and convert it to XLSX.

The answers to this question show how to do this:

  • Load the CSV file using the csv library and then
  • Write it out to XLSX using openpyxl
import csv
import openpyxl

wb = openpyxl.Workbook()
ws = wb.active

with open('file.csv') as f:
    reader = csv.reader(f)
    for row in reader:
        ws.append(row)

wb.save('file.xlsx')

The CSV file is read with open. As the csv docs warn :

Since open() is used to open a CSV file for reading, the file will by default be decoded into unicode using the system default encoding (see locale.getpreferredencoding()). To decode a file using a different encoding, use the encoding argument of open

You may have to use the utf-8, utf-8-sig or utf-16-le encodings:

with open('file.csv', encoding='utf-8') as f:
Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236