Search…

Trích Xuất Dữ Liệu từ File Excel bằng Python - Phần 2: Ghi Dữ Liệu

29/09/20202 min read
Hướng dẫn cách trích xuất dữ liệu từ file excel bằng Python.

Hiện thực

Cài đặt gói xlwt

Truy cập https://pypi.org/project/xlwt/#files để tải gói xlwt về máy:

Tải gói xlwt để trích xuất dữ liệu excel trong Python.

Giải nén và vào thư mục để chạy cmd:

Vào thư mục chứ gói xlwt để chạy cmd.

Cửa sổ cmd hiện lên gõ vào dòng lệnh sau để tiến hành cài đặt:

python setup.py install
Cài đặt gói xlwt trong python

Sau khi cài đặt thành công:

Kết quả cài đặt thành công gói xlwt

Ghi dữ liệu

Tạo Workbook

Tạo Workbook và các sheet:

from xlwt import Workbook

wb = Workbook()
sheet1 = wb.add_sheet('sheet 1')
sheet2 = wb.add_sheet('sheet 2')
sheet3 = wb.add_sheet('sheet 3')

wb.save('demo_xlwt.xls')

Kết quả

Tạo file excel từ thư viện xlwt trong python

File được tạo ra sẽ mặc định ở cùng thư mục với file Python.

Ghi dữ liệu

Xét ví dụ sau:

from xlwt import Workbook

wb = Workbook()
sheet1 = wb.add_sheet('sheet 1')
sheet2 = wb.add_sheet('sheet 2')
sheet3 = wb.add_sheet('sheet 3')

# Write data in sheet 1
sheet1.write(0, 0, 'STT')
sheet1.write(0, 1, 'Name')

wb.save('demo_xlwt.xls')

Ghi được dữ liệu vào sheet 1:

Ghi dữ liệu vào sheet trong file excel bằng thư viện xlwt trong Python

Thay sheet1 bằng các biến khác để ghi vào các sheet tương ứng khác của Workbook.

Tạo trước một dữ liệu sau đó ghi vào Workbook như sau:

from xlwt import Workbook

wb = Workbook()
sheet1 = wb.add_sheet('sheet 1')
sheet2 = wb.add_sheet('sheet 2')
sheet3 = wb.add_sheet('sheet 3')

# Write data in sheet 1
sheet1.write(0, 0, 'STT')
sheet1.write(0, 1, 'Name')

# data
author_stdio = (
    [1, 'La Kiến Vinh'],
    [2, 'Vũ Quang Huy'],
    [3, 'Ryan Le'],
)

# Start from the first cell. Rows and columns are zero indexed.
row = 1
col = 0

# Iterate over the data and write it out row by row.
for item, cost in (author_stdio):
    sheet1.write(row, col,     item)
    sheet1.write(row, col + 1, cost)
    row += 1


wb.save('demo_xlwt.xls')

Kết quả:

Điều chỉnh độ rộng của một cột:

sheet1.col(1).width = 7000

Nhập công thức cho một ô tính:

from xlwt import Formula
sheet1.write(3, 1, Formula('SUM(A2:A4)'))

Link download file demo

IO Stream

IO Stream Co., Ltd

30 Trinh Dinh Thao, Hoa Thanh ward, Tan Phu district, Ho Chi Minh city, Vietnam
+84 28 22 00 11 12
developer@iostream.co

383/1 Quang Trung, ward 10, Go Vap district, Ho Chi Minh city
Business license number: 0311563559 issued by the Department of Planning and Investment of Ho Chi Minh City on February 23, 2012

©IO Stream, 2013 - 2024