[python] How to convert data between csv and xlsx

Table of contents

1. Write data from xlsx to csv

        1. Use pandas

        2. Do not use pandas

2. Write data from csv to xlsx

        1. Use pandas        

        2. Do not use pandas


1. Write data from xlsx to csv

        1. Use pandas

        To write data from an XLSX (Excel) file into a CSV file, you can use Python's pandaslibrary.

        Here is an example program:

import pandas as pd

# 从XLSX文件读取数据
df = pd.read_excel('input.xlsx')

# 将数据写入CSV文件
df.to_csv('output.csv', index=False)

In the above example, we first pd.read_excel()read the data from the XLSX file using the method and store it as a DataFrame object df. We then use df.to_csv()the method to write the data to a CSV file, which index=Falseindicates that the index column is not included.

Please note that before running this example, you need to install pandasthe library first, you can use the following command to install it:

pip install pandas

With the method described above, you can write data from an XLSX file into a CSV file to use the data in CSV format in other applications or environments. 

        2. Do not use pandas

        If you are not using pandasa library, you can use openpyxlthe and csvmodules to write data from an XLSX file into a CSV file.

Here is an example program:

import openpyxl
import csv

# 打开XLSX文件
wb = openpyxl.load_workbook('input.xlsx')

# 选择第一个工作表
sheet = wb.active

# 打开CSV文件
with open('output.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile)

    # 遍历工作表的行
    for row in sheet.iter_rows(values_only=True):
        writer.writerow(row)

# 关闭XLSX文件
wb.close()
  • In the above code, for row in sheet.iter_rows(values_only=True)a loop statement is used to traverse each row of data in the worksheet.
  • sheet.iter_rows()Yes openpyxlA method of the worksheet object in the library that iterates through the rows of the worksheet. By setting values_only=True, we can directly get the value of each cell instead of a tuple containing the cell object.
  • In each loop, rowthe variable represents the current row's data. In the next line of code, we use writer.writerow(row)to write the current row's data to the CSV file.
  • By using sheet.iter_rows(values_only=True), we can easily iterate through each row of the worksheet and access the data in it without using complicated indexes or methods to get the value of the cell.

 

2. Write data from csv to xlsx

        1. Use pandas        

        To write data from a CSV file to an XLSX (Excel) file, you can use Python's pandaslibraries and openpyxllibraries. pandasThe library provides convenience methods to read and process CSV files, while openpyxlthe library is used to create and write Excel files.

Here is an example program:

import pandas as pd

# 从CSV文件读取数据
df = pd.read_csv('input.csv')

# 创建Excel Writer对象
writer = pd.ExcelWriter('output.xlsx', engine='openpyxl')

# 将数据写入Excel文件
df.to_excel(writer, index=False)

# 保存并关闭Excel文件
writer.save()
writer.close()

In the above example, we first pd.read_csv()read the data from the CSV file using the method and store it as a DataFrame object df. Then, we create an Excel Writer object and specify it as openpyxlthe engine. Next, we df.to_excel()write the data to the Excel file using the method, which index=Falseindicates that the index column is not included. Finally, we writer.save()save and close the Excel file using . 

Note that in order to run this example, you need to have the pandasand openpyxllibraries installed first, you can use the following commands to install them: 

pip install pandas openpyxl

Through the above methods, you can conveniently write data from CSV files to XLSX files, and perform further Excel file operations as needed.

        2. Do not use pandas

       If you are not using pandasa library, you can use openpyxlthe and csvmodules to write data from a CSV file into an XLSX file.

Here is an example program:

import openpyxl
import csv

# 创建新的XLSX文件
wb = openpyxl.Workbook()
sheet = wb.active

# 打开CSV文件
with open('input.csv', 'r') as csvfile:
    reader = csv.reader(csvfile)

    # 遍历CSV文件的行
    for row in reader:
        sheet.append(row)

# 保存XLSX文件
wb.save('output.xlsx')
  • In the above example, we first created a new XLSX file and got its default active sheet (via wb.active). We then use the built-in csvmodule to open the CSV file and create an csv.readerobject to read the data from.
  • Next, we for row in readeriterate through each row of the CSV file using a loop and sheet.append(row)add each row to a sheet in the XLSX file using
  • Finally, we wb.save()save the XLSX file using the method.

Guess you like

Origin blog.csdn.net/weixin_43569834/article/details/131406292