简体   繁体   English

从 Microsoft excel csv 文件复制范围

[英]Copy range from Microsoft excel csv file

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?有没有办法将单元格范围从 Microsoft excel csv 复制到同一文件中的其他单元格,就像普通的 .xlsx 文件一样,或者复制到新的 .xlsx 文件?

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.替代方法是简单地将此文件保存为 .xlsx 格式,但由于 UTF-16 LE 编码,我在使用此方法时也遇到了问题。

There are no Excel CSV files.没有Excel CSV文件。 CSV is a flat text file with a specific, minimal format. CSV 是具有特定最小格式的纯文本文件。 xlsx files on the other hand are ZIP packages containing XML files.另一方面, xlsx文件是包含 XML 文件的 ZIP 包。 I suspect what you really ask is how to read a CSV text file saved with one encoding and convert it to XLSX.我怀疑您真正要问的是如何读取使用一种编码保存的 CSV 文本文件并将其转换为 XLSX。

The answers to this question show how to do this: 这个问题的答案显示了如何做到这一点:

  • Load the CSV file using the csv library and then使用csv库加载 CSV 文件,然后
  • Write it out to XLSX using openpyxl使用openpyxl将其写出到 XLSX
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 . CSV 文件使用open读取。 As the csv docs warn :正如csv文档警告的那样:

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()).由于 open() 用于打开 CSV 文件进行读取,因此默认情况下该文件将使用系统默认编码解码为 un​​icode(请参阅 locale.getpreferredencoding())。 To decode a file using a different encoding, use the encoding argument of open要使用不同的编码解码文件,请使用 open 的 encoding 参数

You may have to use the utf-8 , utf-8-sig or utf-16-le encodings:您可能必须使用utf-8utf-8-sigutf-16-le编码:

with open('file.csv', encoding='utf-8') as f:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM