Có một vài hành động cơ bản mà bạn sẽ làm với các tài liệu Microsoft Excel. Một trong những cơ bản nhất là hành động đọc dữ liệu từ tệp Excel. Bạn sẽ học cách lấy dữ liệu từ bảng tính Excel của bạn.
Lưu ý của biên tập viên: Bài viết này dựa trên một chương từ cuốn sách: Tự động hóa Excel với Python. Bạn có thể đặt một bản sao trên Gumroador Kickstarter. or Kickstarter.
Trước khi bạn đi sâu vào tự động hóa Excel với Python, bạn nên hiểu một số thuật ngữ phổ biến:
- Bảng tính hoặc sổ làm việc - bản thân tệp [.xls hoặc .xlsx].
- Bảng tính hoặc tờ - Một trang nội dung duy nhất trong sổ làm việc. Bảng tính có thể chứa nhiều bảng tính.
- Cột - Một dòng dữ liệu thẳng đứng được dán nhãn bằng các chữ cái, bắt đầu bằng cách A A.
- Hàng - Một dòng dữ liệu nằm ngang được dán nhãn số, bắt đầu bằng 1.
- Ô - sự kết hợp giữa cột và hàng, như là A1 A1.
Bây giờ bạn có một số hiểu biết cơ bản về từ vựng, bạn có thể tiếp tục.
Trong chương này, bạn sẽ học cách thực hiện các nhiệm vụ sau:
- Mở một bảng tính
- Đọc các ô cụ thể
- Đọc các ô từ một hàng cụ thể
- Đọc các ô từ một cột cụ thể
- Đọc các ô từ nhiều hàng hoặc cột
- Đọc các ô từ một phạm vi
- Đọc tất cả các ô trong tất cả các tờ
Bạn có thể bắt đầu bằng cách học cách mở sổ làm việc trong phần tiếp theo!
Mở một bảng tính
Mục đầu tiên mà bạn cần là tệp Microsoft Excel. Bạn có thể sử dụng tệp trong kho lưu trữ mã GitHub này. Có một tệp trong thư mục Chương 2 có tên
# read_specific_sheet.py from openpyxl import load_workbook def open_workbook[path, sheet_name]: workbook = load_workbook[filename=path] if sheet_name in workbook.sheetnames: sheet = workbook[sheet_name] print[f"The title of the Worksheet is: {sheet.title}"] print[f"Cells that contain data: {sheet.calculate_dimension[]}"] if __name__ == "__main__": open_workbook["books.xlsx", sheet_name="Sales"]6 mà bạn sẽ sử dụng ở đây.GitHub code repository. There is a file in the chapter 2 folder called
# read_specific_sheet.py from openpyxl import load_workbook def open_workbook[path, sheet_name]: workbook = load_workbook[filename=path] if sheet_name in workbook.sheetnames: sheet = workbook[sheet_name] print[f"The title of the Worksheet is: {sheet.title}"] print[f"Cells that contain data: {sheet.calculate_dimension[]}"] if __name__ == "__main__": open_workbook["books.xlsx", sheet_name="Sales"]6 that you will use here.
Nó có hai tờ trong đó. Dưới đây là ảnh chụp màn hình của tờ đầu tiên:
Để hoàn thiện, đây là ảnh chụp màn hình của tờ thứ hai:
Lưu ý: Dữ liệu trong các bảng này là không chính xác, nhưng chúng giúp tìm hiểu cách sử dụng openpyxl.
Bây giờ bạn đã sẵn sàng để bắt đầu mã hóa! Mở ra trình soạn thảo Python yêu thích của bạn và tạo một tệp mới có tên
# read_specific_sheet.py from openpyxl import load_workbook def open_workbook[path, sheet_name]: workbook = load_workbook[filename=path] if sheet_name in workbook.sheetnames: sheet = workbook[sheet_name] print[f"The title of the Worksheet is: {sheet.title}"] print[f"Cells that contain data: {sheet.calculate_dimension[]}"] if __name__ == "__main__": open_workbook["books.xlsx", sheet_name="Sales"]7. Sau đó thêm mã sau vào tệp của bạn:
# open_workbook.py from openpyxl import load_workbook def open_workbook[path]: workbook = load_workbook[filename=path] print[f"Worksheet names: {workbook.sheetnames}"] sheet = workbook.active print[sheet] print[f"The title of the Worksheet is: {sheet.title}"] if __name__ == "__main__": open_workbook["books.xlsx"]
Bước đầu tiên trong mã này là nhập
# read_specific_sheet.py from openpyxl import load_workbook def open_workbook[path, sheet_name]: workbook = load_workbook[filename=path] if sheet_name in workbook.sheetnames: sheet = workbook[sheet_name] print[f"The title of the Worksheet is: {sheet.title}"] print[f"Cells that contain data: {sheet.calculate_dimension[]}"] if __name__ == "__main__": open_workbook["books.xlsx", sheet_name="Sales"]8 từ gói
# read_specific_sheet.py from openpyxl import load_workbook def open_workbook[path, sheet_name]: workbook = load_workbook[filename=path] if sheet_name in workbook.sheetnames: sheet = workbook[sheet_name] print[f"The title of the Worksheet is: {sheet.title}"] print[f"Cells that contain data: {sheet.calculate_dimension[]}"] if __name__ == "__main__": open_workbook["books.xlsx", sheet_name="Sales"]9. Hàm
# read_specific_sheet.py from openpyxl import load_workbook def open_workbook[path, sheet_name]: workbook = load_workbook[filename=path] if sheet_name in workbook.sheetnames: sheet = workbook[sheet_name] print[f"The title of the Worksheet is: {sheet.title}"] print[f"Cells that contain data: {sheet.calculate_dimension[]}"] if __name__ == "__main__": open_workbook["books.xlsx", sheet_name="Sales"]8 sẽ tải lên tệp Excel của bạn và trả về nó dưới dạng đối tượng Python. Sau đó, bạn có thể tương tác với đối tượng Python đó giống như bất kỳ đối tượng nào khác trong Python.
Bạn có thể nhận được một danh sách các bảng tính trong tệp Excel bằng cách truy cập thuộc tính
# reading_specific_cells.py from openpyxl import load_workbook def get_cell_info[path]: workbook = load_workbook[filename=path] sheet = workbook.active print[sheet] print[f'The title of the Worksheet is: {sheet.title}'] print[f'The value of A2 is {sheet["A2"].value}'] print[f'The value of A3 is {sheet["A3"].value}'] cell = sheet['B3'] print[f'The variable "cell" is {cell.value}'] if __name__ == '__main__': get_cell_info['books.xlsx']1. Danh sách này chứa các tiêu đề của bảng tính từ trái sang phải trong tệp Excel của bạn. Mã của bạn sẽ in ra danh sách này.
Tiếp theo, bạn lấy tờ hiện đang hoạt động. Nếu sổ làm việc của bạn chỉ có một bảng tính, thì bảng đó sẽ là bản hoạt động. Nếu sổ làm việc của bạn có nhiều bảng tính, như cái này, thì bảng tính cuối cùng sẽ là hoạt động.
Hai dòng cuối cùng của chức năng của bạn in ra đối tượng
# reading_specific_cells.py from openpyxl import load_workbook def get_cell_info[path]: workbook = load_workbook[filename=path] sheet = workbook.active print[sheet] print[f'The title of the Worksheet is: {sheet.title}'] print[f'The value of A2 is {sheet["A2"].value}'] print[f'The value of A3 is {sheet["A3"].value}'] cell = sheet['B3'] print[f'The variable "cell" is {cell.value}'] if __name__ == '__main__': get_cell_info['books.xlsx']2 và tiêu đề của bảng tính hoạt động.
Điều gì sẽ xảy ra nếu bạn muốn chọn một bảng tính cụ thể để làm việc, mặc dù? Để tìm hiểu cách thực hiện điều đó, hãy tạo một tệp mới và đặt tên cho nó
# reading_specific_cells.py from openpyxl import load_workbook def get_cell_info[path]: workbook = load_workbook[filename=path] sheet = workbook.active print[sheet] print[f'The title of the Worksheet is: {sheet.title}'] print[f'The value of A2 is {sheet["A2"].value}'] print[f'The value of A3 is {sheet["A3"].value}'] cell = sheet['B3'] print[f'The variable "cell" is {cell.value}'] if __name__ == '__main__': get_cell_info['books.xlsx']3.
Sau đó nhập mã sau:
# read_specific_sheet.py from openpyxl import load_workbook def open_workbook[path, sheet_name]: workbook = load_workbook[filename=path] if sheet_name in workbook.sheetnames: sheet = workbook[sheet_name] print[f"The title of the Worksheet is: {sheet.title}"] print[f"Cells that contain data: {sheet.calculate_dimension[]}"] if __name__ == "__main__": open_workbook["books.xlsx", sheet_name="Sales"]
Chức năng của bạn,
# reading_specific_cells.py from openpyxl import load_workbook def get_cell_info[path]: workbook = load_workbook[filename=path] sheet = workbook.active print[sheet] print[f'The title of the Worksheet is: {sheet.title}'] print[f'The value of A2 is {sheet["A2"].value}'] print[f'The value of A3 is {sheet["A3"].value}'] cell = sheet['B3'] print[f'The variable "cell" is {cell.value}'] if __name__ == '__main__': get_cell_info['books.xlsx']4 hiện chấp nhận
# reading_specific_cells.py from openpyxl import load_workbook def get_cell_info[path]: workbook = load_workbook[filename=path] sheet = workbook.active print[sheet] print[f'The title of the Worksheet is: {sheet.title}'] print[f'The value of A2 is {sheet["A2"].value}'] print[f'The value of A3 is {sheet["A3"].value}'] cell = sheet['B3'] print[f'The variable "cell" is {cell.value}'] if __name__ == '__main__': get_cell_info['books.xlsx']5.
# reading_specific_cells.py from openpyxl import load_workbook def get_cell_info[path]: workbook = load_workbook[filename=path] sheet = workbook.active print[sheet] print[f'The title of the Worksheet is: {sheet.title}'] print[f'The value of A2 is {sheet["A2"].value}'] print[f'The value of A3 is {sheet["A3"].value}'] cell = sheet['B3'] print[f'The variable "cell" is {cell.value}'] if __name__ == '__main__': get_cell_info['books.xlsx']5 là một chuỗi phù hợp với tiêu đề của bảng tính mà bạn muốn đọc. Bạn kiểm tra xem
# reading_specific_cells.py from openpyxl import load_workbook def get_cell_info[path]: workbook = load_workbook[filename=path] sheet = workbook.active print[sheet] print[f'The title of the Worksheet is: {sheet.title}'] print[f'The value of A2 is {sheet["A2"].value}'] print[f'The value of A3 is {sheet["A3"].value}'] cell = sheet['B3'] print[f'The variable "cell" is {cell.value}'] if __name__ == '__main__': get_cell_info['books.xlsx']5 có nằm trong mã của bạn không. Nếu đúng như vậy, bạn chọn bảng đó bằng cách truy cập nó bằng
# reading_specific_cells.py from openpyxl import load_workbook def get_cell_info[path]: workbook = load_workbook[filename=path] sheet = workbook.active print[sheet] print[f'The title of the Worksheet is: {sheet.title}'] print[f'The value of A2 is {sheet["A2"].value}'] print[f'The value of A3 is {sheet["A3"].value}'] cell = sheet['B3'] print[f'The variable "cell" is {cell.value}'] if __name__ == '__main__': get_cell_info['books.xlsx']9.
Sau đó, bạn in ra tiêu đề của trang tính để xác minh rằng bạn có đúng trang tính. Bạn cũng gọi một cái gì đó mới:
The title of the Worksheet is: Sales The value of A2 is 'Python 101' The value of A3 is 'wxPython Recipes' The variable "cell" is 50. Phương pháp đó trả về các ô chứa dữ liệu trong bảng tính. Trong trường hợp này, nó sẽ in ra rằng "A1: D4" có dữ liệu trong đó.
Bây giờ bạn đã sẵn sàng để tiếp tục và tìm hiểu cách đọc dữ liệu từ chính các ô.
Đọc các ô cụ thể
Có rất nhiều cách khác nhau để đọc các ô bằng OpenPyXL. Để bắt đầu mọi thứ, bạn sẽ học cách đọc nội dung của các ô cụ thể.
Tạo một tệp mới trong trình soạn thảo Python của bạn và đặt tên cho nó
The title of the Worksheet is: Sales The value of A2 is 'Python 101' The value of A3 is 'wxPython Recipes' The variable "cell" is 51. Sau đó nhập mã sau:
# reading_specific_cells.py from openpyxl import load_workbook def get_cell_info[path]: workbook = load_workbook[filename=path] sheet = workbook.active print[sheet] print[f'The title of the Worksheet is: {sheet.title}'] print[f'The value of A2 is {sheet["A2"].value}'] print[f'The value of A3 is {sheet["A3"].value}'] cell = sheet['B3'] print[f'The variable "cell" is {cell.value}'] if __name__ == '__main__': get_cell_info['books.xlsx']
Trong ví dụ này, có ba ô mã hóa cứng: A2, A3 và B3. Bạn có thể truy cập các giá trị của họ bằng cách sử dụng quyền truy cập giống như từ điển:
The title of the Worksheet is: Sales The value of A2 is 'Python 101' The value of A3 is 'wxPython Recipes' The variable "cell" is 52. Ngoài ra, bạn có thể gán
The title of the Worksheet is: Sales The value of A2 is 'Python 101' The value of A3 is 'wxPython Recipes' The variable "cell" is 53 cho một biến và sau đó làm một cái gì đó như
The title of the Worksheet is: Sales The value of A2 is 'Python 101' The value of A3 is 'wxPython Recipes' The variable "cell" is 54 để có được giá trị của ô.
Bạn có thể thấy cả hai phương pháp này được thể hiện trong mã của bạn ở trên.
Khi bạn chạy mã này, bạn sẽ thấy đầu ra sau:
The title of the Worksheet is: Sales The value of A2 is 'Python 101' The value of A3 is 'wxPython Recipes' The variable "cell" is 5
Đầu ra này cho thấy cách bạn có thể dễ dàng trích xuất các giá trị ô cụ thể từ Excel bằng Python.
Bây giờ bạn đã sẵn sàng để tìm hiểu làm thế nào bạn có thể đọc dữ liệu từ một hàng ô cụ thể!
Đọc các ô từ hàng cụ thể
Trong hầu hết các trường hợp, bạn sẽ muốn đọc nhiều hơn một ô trong một bảng tính tại một thời điểm. OpenPyXL cũng cung cấp một cách để có được toàn bộ hàng cùng một lúc.
Hãy tiếp tục và tạo một tập tin mới. Bạn có thể đặt tên cho nó
The title of the Worksheet is: Sales The value of A2 is 'Python 101' The value of A3 is 'wxPython Recipes' The variable "cell" is 55. Sau đó thêm mã sau vào chương trình của bạn:
# reading_row_cells.py from openpyxl import load_workbook def iterating_row[path, sheet_name, row]: workbook = load_workbook[filename=path] if sheet_name not in workbook.sheetnames: print[f"'{sheet_name}' not found. Quitting."] return sheet = workbook[sheet_name] for cell in sheet[row]: print[f"{cell.column_letter}{cell.row} = {cell.value}"] if __name__ == "__main__": iterating_row["books.xlsx", sheet_name="Sheet 1 - Books", row=2]
Trong ví dụ này, bạn vượt qua hàng số 2. Bạn có thể lặp lại các giá trị trong hàng như thế này:2. You can iterate over the values in the row like this:
for cell in sheet[row]: ...
Điều đó làm cho việc lấy các giá trị từ một hàng khá đơn giản. Khi bạn chạy mã này, bạn sẽ nhận được đầu ra sau:
A2 = Title B2 = Author C2 = Publisher D2 = Publishing Date E2 = ISBN F2 = None G2 = None
Hai giá trị cuối cùng đó đều không có. Nếu bạn không muốn nhận được các giá trị không có, bạn nên thêm một số xử lý thêm để kiểm tra xem giá trị không có trước khi in ra. Bạn có thể cố gắng tìm ra điều đó như một bài tập.None. If you don't want to get values that are None, you should add some extra processing to check if the value is None before printing it out. You can try to figure that out yourself as an exercise.
Bây giờ bạn đã sẵn sàng để tìm hiểu làm thế nào để có được các ô từ một cột cụ thể!
Đọc các ô từ cột cụ thể
Đọc dữ liệu từ một cột cụ thể cũng là một trường hợp sử dụng thường xuyên mà bạn nên biết cách thực hiện. Ví dụ: bạn có thể có một cột chỉ chứa tổng số và bạn chỉ cần trích xuất cột cụ thể đó.
Để xem cách bạn có thể làm điều đó, tạo một tệp mới và đặt tên cho nó
The title of the Worksheet is: Sales The value of A2 is 'Python 101' The value of A3 is 'wxPython Recipes' The variable "cell" is 56. Sau đó nhập mã này:
# reading_column_cells.py from openpyxl import load_workbook def iterating_column[path, sheet_name, col]: workbook = load_workbook[filename=path] if sheet_name not in workbook.sheetnames: print[f"'{sheet_name}' not found. Quitting."] return sheet = workbook[sheet_name] for cell in sheet[col]: print[f"{cell.column_letter}{cell.row} = {cell.value}"] if __name__ == "__main__": iterating_column["books.xlsx", sheet_name="Sheet 1 - Books", col="A"]
Mã này rất giống với mã trong phần trước. Sự khác biệt ở đây là bạn đang thay thế
The title of the Worksheet is: Sales The value of A2 is 'Python 101' The value of A3 is 'wxPython Recipes' The variable "cell" is 57 bằng
The title of the Worksheet is: Sales The value of A2 is 'Python 101' The value of A3 is 'wxPython Recipes' The variable "cell" is 58 và thay vào đó lặp đi lặp lại.
Trong ví dụ này, bạn đặt cột thành "A". Khi bạn chạy mã này, bạn sẽ nhận được đầu ra sau:
A1 = Books A2 = Title A3 = Python 101 A4 = wxPython Recipes A5 = Python Interviews A6 = None A7 = None A8 = None A9 = None A10 = None A11 = None A12 = None A13 = None A14 = None A15 = None A16 = None A17 = None A18 = None A19 = None A20 = None A21 = None A22 = None A23 = None
Một lần nữa, một số cột không có dữ liệu [tức là "không"]. Bạn có thể chỉnh sửa mã này để bỏ qua các ô trống và chỉ xử lý các ô có nội dung.
Bây giờ chúng ta hãy khám phá cách lặp lại trên nhiều cột hoặc hàng!
Đọc các ô từ nhiều hàng hoặc cột
Có hai phương pháp mà các đối tượng bảng tính của OpenPyXL cung cấp cho bạn để lặp lại trên các hàng và cột. Đây là hai phương pháp:
The title of the Worksheet is: Sales The value of A2 is 'Python 101' The value of A3 is 'wxPython Recipes' The variable "cell" is 5
9# reading_row_cells.py from openpyxl import load_workbook def iterating_row[path, sheet_name, row]: workbook = load_workbook[filename=path] if sheet_name not in workbook.sheetnames: print[f"'{sheet_name}' not found. Quitting."] return sheet = workbook[sheet_name] for cell in sheet[row]: print[f"{cell.column_letter}{cell.row} = {cell.value}"] if __name__ == "__main__": iterating_row["books.xlsx", sheet_name="Sheet 1 - Books", row=2]
0
Các phương pháp này được ghi lại khá tốt trong tài liệu của OpenPyXL. Cả hai phương thức đều có các tham số sau:
# reading_row_cells.py from openpyxl import load_workbook def iterating_row[path, sheet_name, row]: workbook = load_workbook[filename=path] if sheet_name not in workbook.sheetnames: print[f"'{sheet_name}' not found. Quitting."] return sheet = workbook[sheet_name] for cell in sheet[row]: print[f"{cell.column_letter}{cell.row} = {cell.value}"] if __name__ == "__main__": iterating_row["books.xlsx", sheet_name="Sheet 1 - Books", row=2]
1 [int]-Chỉ mục cột nhỏ nhất [chỉ mục dựa trên 1]# reading_row_cells.py from openpyxl import load_workbook def iterating_row[path, sheet_name, row]: workbook = load_workbook[filename=path] if sheet_name not in workbook.sheetnames: print[f"'{sheet_name}' not found. Quitting."] return sheet = workbook[sheet_name] for cell in sheet[row]: print[f"{cell.column_letter}{cell.row} = {cell.value}"] if __name__ == "__main__": iterating_row["books.xlsx", sheet_name="Sheet 1 - Books", row=2]
2 [int]-Chỉ mục hàng nhỏ nhất [chỉ mục dựa trên 1]# reading_row_cells.py from openpyxl import load_workbook def iterating_row[path, sheet_name, row]: workbook = load_workbook[filename=path] if sheet_name not in workbook.sheetnames: print[f"'{sheet_name}' not found. Quitting."] return sheet = workbook[sheet_name] for cell in sheet[row]: print[f"{cell.column_letter}{cell.row} = {cell.value}"] if __name__ == "__main__": iterating_row["books.xlsx", sheet_name="Sheet 1 - Books", row=2]
3 [int]-Chỉ số cột lớn nhất [chỉ mục dựa trên 1]# reading_row_cells.py from openpyxl import load_workbook def iterating_row[path, sheet_name, row]: workbook = load_workbook[filename=path] if sheet_name not in workbook.sheetnames: print[f"'{sheet_name}' not found. Quitting."] return sheet = workbook[sheet_name] for cell in sheet[row]: print[f"{cell.column_letter}{cell.row} = {cell.value}"] if __name__ == "__main__": iterating_row["books.xlsx", sheet_name="Sheet 1 - Books", row=2]
4 [int]-Chỉ mục hàng lớn nhất [chỉ mục dựa trên 1]# reading_row_cells.py from openpyxl import load_workbook def iterating_row[path, sheet_name, row]: workbook = load_workbook[filename=path] if sheet_name not in workbook.sheetnames: print[f"'{sheet_name}' not found. Quitting."] return sheet = workbook[sheet_name] for cell in sheet[row]: print[f"{cell.column_letter}{cell.row} = {cell.value}"] if __name__ == "__main__": iterating_row["books.xlsx", sheet_name="Sheet 1 - Books", row=2]
5 [bool] - Cho dù chỉ các giá trị ô nên được trả về
Bạn sử dụng các hàng và tham số cột tối đa và tối đa để cho OpenPyXL biết các hàng và cột nào để lặp lại. Bạn có thể có OpenPyXL trả về dữ liệu từ các ô bằng cách đặt
# reading_row_cells.py from openpyxl import load_workbook def iterating_row[path, sheet_name, row]: workbook = load_workbook[filename=path] if sheet_name not in workbook.sheetnames: print[f"'{sheet_name}' not found. Quitting."] return sheet = workbook[sheet_name] for cell in sheet[row]: print[f"{cell.column_letter}{cell.row} = {cell.value}"] if __name__ == "__main__": iterating_row["books.xlsx", sheet_name="Sheet 1 - Books", row=2]5 thành true. Nếu bạn đặt nó thành sai, thay vào đó,
The title of the Worksheet is: Sales The value of A2 is 'Python 101' The value of A3 is 'wxPython Recipes' The variable "cell" is 59 và
# reading_row_cells.py from openpyxl import load_workbook def iterating_row[path, sheet_name, row]: workbook = load_workbook[filename=path] if sheet_name not in workbook.sheetnames: print[f"'{sheet_name}' not found. Quitting."] return sheet = workbook[sheet_name] for cell in sheet[row]: print[f"{cell.column_letter}{cell.row} = {cell.value}"] if __name__ == "__main__": iterating_row["books.xlsx", sheet_name="Sheet 1 - Books", row=2]0 sẽ trả về các đối tượng ô.
Luôn luôn tốt để xem cách hoạt động của nó với mã thực tế. Với ý nghĩ đó, hãy tạo một tệp mới có tên
# reading_row_cells.py from openpyxl import load_workbook def iterating_row[path, sheet_name, row]: workbook = load_workbook[filename=path] if sheet_name not in workbook.sheetnames: print[f"'{sheet_name}' not found. Quitting."] return sheet = workbook[sheet_name] for cell in sheet[row]: print[f"{cell.column_letter}{cell.row} = {cell.value}"] if __name__ == "__main__": iterating_row["books.xlsx", sheet_name="Sheet 1 - Books", row=2]9 và thêm mã này vào nó:
# iterating_over_cells_in_rows.py from openpyxl import load_workbook def iterating_over_values[path, sheet_name]: workbook = load_workbook[filename=path] if sheet_name not in workbook.sheetnames: print[f"'{sheet_name}' not found. Quitting."] return sheet = workbook[sheet_name] for value in sheet.iter_rows[ min_row=1, max_row=3, min_col=1, max_col=3, values_only=True]: print[value] if __name__ == "__main__": iterating_over_values["books.xlsx", sheet_name="Sheet 1 - Books"]
Ở đây bạn tải lên sổ làm việc như bạn có trong các ví dụ trước. Bạn nhận được tên trang tính mà bạn muốn trích xuất dữ liệu từ và sau đó sử dụng
The title of the Worksheet is: Sales The value of A2 is 'Python 101' The value of A3 is 'wxPython Recipes' The variable "cell" is 59 để lấy các hàng dữ liệu. Trong ví dụ này, bạn đặt hàng tối thiểu thành 1 và hàng tối đa thành 3. Điều đó có nghĩa là bạn sẽ lấy ba hàng đầu tiên trong bảng excel bạn đã chỉ định.
Sau đó, bạn cũng đặt các cột là 1 [tối thiểu] thành 3 [tối đa]. Cuối cùng, bạn đặt
# reading_row_cells.py from openpyxl import load_workbook def iterating_row[path, sheet_name, row]: workbook = load_workbook[filename=path] if sheet_name not in workbook.sheetnames: print[f"'{sheet_name}' not found. Quitting."] return sheet = workbook[sheet_name] for cell in sheet[row]: print[f"{cell.column_letter}{cell.row} = {cell.value}"] if __name__ == "__main__": iterating_row["books.xlsx", sheet_name="Sheet 1 - Books", row=2]5 thành
for cell in sheet[row]: ...2.
Khi bạn chạy mã này, bạn sẽ nhận được đầu ra sau:
# read_specific_sheet.py from openpyxl import load_workbook def open_workbook[path, sheet_name]: workbook = load_workbook[filename=path] if sheet_name in workbook.sheetnames: sheet = workbook[sheet_name] print[f"The title of the Worksheet is: {sheet.title}"] print[f"Cells that contain data: {sheet.calculate_dimension[]}"] if __name__ == "__main__": open_workbook["books.xlsx", sheet_name="Sales"]0
Chương trình của bạn sẽ in ra ba cột đầu tiên của ba hàng đầu tiên trong bảng tính Excel của bạn. Chương trình của bạn in các hàng dưới dạng bộ dữ liệu với ba mục trong đó. Bạn đang sử dụng
The title of the Worksheet is: Sales The value of A2 is 'Python 101' The value of A3 is 'wxPython Recipes' The variable "cell" is 59 như một cách nhanh chóng để lặp lại trên các hàng và cột trong bảng tính Excel bằng Python.
Bây giờ bạn đã sẵn sàng để tìm hiểu cách đọc các ô trong một phạm vi cụ thể.
Đọc các ô từ một phạm vi
Excel cho phép bạn chỉ định một loạt các ô bằng định dạng sau: [col] [hàng] :[ col] [hàng]. Nói cách khác, bạn có thể nói rằng bạn muốn bắt đầu trong cột A, hàng 1, sử dụng A1. Nếu bạn muốn chỉ định một phạm vi, bạn sẽ sử dụng một cái gì đó như thế này: A1: B6. Điều đó nói với Excel rằng bạn đang chọn các ô bắt đầu từ A1 và sẽ đến B6.A1. If you wanted to specify a range, you would use something like this: A1:B6. That tells Excel that you are selecting the cells starting at A1 and going to B6.
Hãy tiếp tục và tạo một tệp mới có tên
for cell in sheet[row]: ...4. Sau đó thêm mã này vào nó:
# read_specific_sheet.py from openpyxl import load_workbook def open_workbook[path, sheet_name]: workbook = load_workbook[filename=path] if sheet_name in workbook.sheetnames: sheet = workbook[sheet_name] print[f"The title of the Worksheet is: {sheet.title}"] print[f"Cells that contain data: {sheet.calculate_dimension[]}"] if __name__ == "__main__": open_workbook["books.xlsx", sheet_name="Sales"]1
Ở đây bạn vượt qua
for cell in sheet[row]: ...5 của mình và lặp lại trong phạm vi đó bằng cách sử dụng vòng lặp
for cell in sheet[row]: ...6 sau:
# read_specific_sheet.py from openpyxl import load_workbook def open_workbook[path, sheet_name]: workbook = load_workbook[filename=path] if sheet_name in workbook.sheetnames: sheet = workbook[sheet_name] print[f"The title of the Worksheet is: {sheet.title}"] print[f"Cells that contain data: {sheet.calculate_dimension[]}"] if __name__ == "__main__": open_workbook["books.xlsx", sheet_name="Sales"]2
Bạn kiểm tra xem tế bào mà bạn đang trích xuất có phải là
for cell in sheet[row]: ...7 không. Nếu có, bạn bỏ qua nó. Nếu không, bạn in ra tên ô và giá trị của nó.
Khi bạn chạy mã này, bạn sẽ thấy đầu ra sau:
# read_specific_sheet.py from openpyxl import load_workbook def open_workbook[path, sheet_name]: workbook = load_workbook[filename=path] if sheet_name in workbook.sheetnames: sheet = workbook[sheet_name] print[f"The title of the Worksheet is: {sheet.title}"] print[f"Cells that contain data: {sheet.calculate_dimension[]}"] if __name__ == "__main__": open_workbook["books.xlsx", sheet_name="Sales"]3
Điều đó làm việc khá tốt. Bạn nên dành một chút thời gian và thử một vài biến thể phạm vi khác để xem nó thay đổi đầu ra như thế nào.
Lưu ý: Mặc dù hình ảnh của "Tờ 1 - Sách" trông giống như ô A1 khác với ô B1 -G1 được hợp nhất, A1 thực sự là một phần của ô được hợp nhất đó.
Ví dụ mã cuối cùng mà bạn sẽ tạo sẽ đọc tất cả dữ liệu trong tài liệu Excel của bạn!
Đọc tất cả các ô trong tất cả các tờ
Microsoft Excel không đơn giản để đọc như tệp CSV hoặc tệp văn bản thông thường. Đó là bởi vì Excel cần lưu trữ dữ liệu của mỗi ô, bao gồm vị trí, định dạng và giá trị của nó và giá trị đó có thể là một số, một ngày, hình ảnh, một liên kết, v.v. Do đó, đọc một tệp excel là rất nhiều công việc! Openpyxl làm tất cả những công việc khó khăn cho chúng tôi, mặc dù.
Cách tự nhiên để lặp qua một tệp Excel là đọc các tờ từ trái sang phải, và trong mỗi tờ, bạn sẽ đọc nó từng hàng, từ trên xuống dưới. Đó là những gì bạn sẽ học cách làm trong phần này.
Bạn sẽ lấy những gì bạn đã học trong các phần trước và áp dụng nó ở đây. Tạo một tệp mới và đặt tên cho nó
for cell in sheet[row]: ...8. Sau đó nhập mã sau:
# read_specific_sheet.py from openpyxl import load_workbook def open_workbook[path, sheet_name]: workbook = load_workbook[filename=path] if sheet_name in workbook.sheetnames: sheet = workbook[sheet_name] print[f"The title of the Worksheet is: {sheet.title}"] print[f"Cells that contain data: {sheet.calculate_dimension[]}"] if __name__ == "__main__": open_workbook["books.xlsx", sheet_name="Sales"]4
Ở đây bạn tải lên sổ làm việc như trước, nhưng lần này bạn đã lặp lại
# reading_specific_cells.py from openpyxl import load_workbook def get_cell_info[path]: workbook = load_workbook[filename=path] sheet = workbook.active print[sheet] print[f'The title of the Worksheet is: {sheet.title}'] print[f'The value of A2 is {sheet["A2"].value}'] print[f'The value of A3 is {sheet["A3"].value}'] cell = sheet['B3'] print[f'The variable "cell" is {cell.value}'] if __name__ == '__main__': get_cell_info['books.xlsx']1. Bạn in ra từng tên trang khi bạn chọn nó. Bạn sử dụng vòng lặp
for cell in sheet[row]: ...6 lồng nhau để lặp qua các hàng và ô để trích xuất dữ liệu từ bảng tính của bạn.
Một lần nữa, bạn bỏ qua
A2 = Title B2 = Author C2 = Publisher D2 = Publishing Date E2 = ISBN F2 = None G2 = None1 vì giá trị của chúng là
A2 = Title B2 = Author C2 = Publisher D2 = Publishing Date E2 = ISBN F2 = None G2 = None2 - giá trị thực tế nằm trong ô bình thường mà
for cell in sheet[row]: ...7 được hợp nhất. Nếu bạn chạy mã này, bạn sẽ thấy rằng nó sẽ in tất cả dữ liệu từ hai bảng tính.
Bạn có thể đơn giản hóa mã này một chút bằng cách sử dụng
The title of the Worksheet is: Sales The value of A2 is 'Python 101' The value of A3 is 'wxPython Recipes' The variable "cell" is 59. Mở một tệp mới và đặt tên cho nó
A2 = Title B2 = Author C2 = Publisher D2 = Publishing Date E2 = ISBN F2 = None G2 = None5. Sau đó nhập như sau:
# read_specific_sheet.py from openpyxl import load_workbook def open_workbook[path, sheet_name]: workbook = load_workbook[filename=path] if sheet_name in workbook.sheetnames: sheet = workbook[sheet_name] print[f"The title of the Worksheet is: {sheet.title}"] print[f"Cells that contain data: {sheet.calculate_dimension[]}"] if __name__ == "__main__": open_workbook["books.xlsx", sheet_name="Sales"]5
Trong mã này, bạn một lần nữa lặp lại tên trang tính trong tài liệu Excel. Tuy nhiên, thay vì lặp qua các hàng và cột, bạn sử dụng
The title of the Worksheet is: Sales The value of A2 is 'Python 101' The value of A3 is 'wxPython Recipes' The variable "cell" is 59 để lặp chỉ trên các hàng. Bạn đặt
# reading_row_cells.py from openpyxl import load_workbook def iterating_row[path, sheet_name, row]: workbook = load_workbook[filename=path] if sheet_name not in workbook.sheetnames: print[f"'{sheet_name}' not found. Quitting."] return sheet = workbook[sheet_name] for cell in sheet[row]: print[f"{cell.column_letter}{cell.row} = {cell.value}"] if __name__ == "__main__": iterating_row["books.xlsx", sheet_name="Sheet 1 - Books", row=2]5 thành
for cell in sheet[row]: ...2 sẽ trả về một bộ giá trị cho mỗi hàng. Bạn cũng không đặt các hàng hoặc cột tối thiểu và tối đa cho
The title of the Worksheet is: Sales The value of A2 is 'Python 101' The value of A3 is 'wxPython Recipes' The variable "cell" is 59 vì bạn muốn lấy tất cả dữ liệu.
Khi bạn chạy mã này, bạn sẽ thấy nó in ra tên của mỗi tờ, sau đó tất cả dữ liệu trong bảng đó, từng hàng. Hãy thử nó trên bảng tính Excel của riêng bạn và xem mã này có thể làm gì!
Gói lên
OpenPyXL cho phép bạn đọc bảng tính Excel và dữ liệu của nó theo nhiều cách khác nhau. Bạn có thể trích xuất các giá trị từ bảng tính của mình một cách nhanh chóng với số lượng mã tối thiểu.
Trong chương này, bạn đã học cách làm như sau:
- Mở một bảng tính
- Đọc các ô cụ thể
- Đọc các ô từ một hàng cụ thể
- Đọc các ô từ một cột cụ thể
- Đọc các ô từ nhiều hàng hoặc cột
- Đọc các ô từ một phạm vi
- Đọc tất cả các ô trong tất cả các tờ
Bây giờ bạn đã sẵn sàng để tìm hiểu cách tạo bảng tính Excel bằng OpenPyXL. Đó là chủ đề của bài viết tiếp theo trong loạt bài này!