Member-only story
Python 5 ways to write tables — double work efficiency!
1. Use openpyxl library
Openpyxl is a Python library for reading and writing Excel 2010 xlsx/xlsm/xltx/xltm files. It is very powerful and can be used to create complex spreadsheets.
import openpyxl
workbook = openpyxl.Workbook()
sheet = workbook.active
sheet['A1'] = 'Hello'
sheet['B1'] = 'World'
workbook.save('example.xlsx')
2. Use the pandas library
Pandas is a powerful data processing library that provides DataFrame data structures, which are very suitable for manipulating tabular data.
import pandas as pd
data = {'A': [1, 2, 3], 'B': ['a', 'b', 'c']}
df = pd.DataFrame(data)
df.to_excel('example_pandas.xlsx', index=False)
3. Use xlwt and xlrd libraries
Xlwt is used to write to Excel files, while xlrd is used to read Excel files. These two libraries are usually used to handle older XLS formats.
import xlwt
workbook = xlwt.Workbook()
sheet = workbook.add_sheet('Sheet1')
sheet.write(0, 0, 'Hello')
workbook.save('example.xls')
4. Use the xlsxwriter library
Xlsxwriter supports the .xlsx format of Excel and can create complex charts and formats.
import xlsxwriter
workbook = xlsxwriter.Workbook('example.xlsx')
worksheet = workbook.add_worksheet()
worksheet.write('A1', 'Hello World')
workbook.close()
5. csv module
The CSV module can handle CSV files and is a common table data storage format.
import csv
with open('example.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['A', 'B', 'C'])
writer.writerow([1, 2, 3])