befaint
|||||||||||||
- Tham gia
- 6/1/11
- Bài viết
- 14,581
- Được thích
- 19,782
Xem bài viết Python với Excel - Mở đầu và cài đặt thư viện để cài đặt Python và thư viện cần thiết.
Mượn chủ đề này: Lỗi Khi lấy dữ liệu bằng ADO để viết xử lý bằng Python.
Mô tả: Cần lấy dữ liệu ở một file1 và ghi vào một file2 khác. Công việc lặp lại theo chu kỳ/ yêu cầu nào đó, dữ liệu mới ghi vào sẽ ghi nối tiếp vào phía dưới của file2.
Trong bài này có sử dụng module tkinter để mở cửa sổ cho phép chọn file Excel theo mong muốn..
Tải file dưới, giải nén và mở file read_write_data.py bằng IDLE của Python rồi nhấn F5..
(Đừng bất ngờ về tốc độ đọc và ghi dữ liệu).

Mượn chủ đề này: Lỗi Khi lấy dữ liệu bằng ADO để viết xử lý bằng Python.
Mô tả: Cần lấy dữ liệu ở một file1 và ghi vào một file2 khác. Công việc lặp lại theo chu kỳ/ yêu cầu nào đó, dữ liệu mới ghi vào sẽ ghi nối tiếp vào phía dưới của file2.
Trong bài này có sử dụng module tkinter để mở cửa sổ cho phép chọn file Excel theo mong muốn..
PHP:
from openpyxl import load_workbook
import tkinter as tk
from tkinter import filedialog
def select_excel_file(idex_title):
""" idex_title = 1 -> File cần lấy dữ liệu
idex_title = 2 -> File ghi dữ liệu vào """
titles = {1: "Chọn file cần lấy dữ liệu", 2: "Chọn file cần ghi dữ liệu vào"}
excel_filetypes = [('Excel files', '*.xls*'), ('All files', '*')]
root = tk.Tk()
root.withdraw()
file_path = ""
file_path = filedialog.askopenfilename(title = titles[idex_title], filetypes = excel_filetypes)
return file_path
def Read_Write(start_row, last_column):
""" Lấy dữ liệu trong sheets(1) của excel_file1
rồi ghi (nối tiếp các lần lấy) vào file excel_file2
start_row = 8 # dòng đầu tiên cần lấy dữ liệu trong excel_file1
last_column = 18 # cột cuối cùng cần lấy dữ liệu trong excel_file1, mặc định lấy từ cột đầu tiên của bảng tính """
s_file = select_excel_file(1) # chọn file cần lấy dữ liệu
if len(s_file) > 0:
d_file = select_excel_file(2) # chọn file cần ghi dữ liệu vào
if len(d_file) > 0:
# load excel_file1
wb_1 = load_workbook(s_file)
ws_1 = wb_1.active
lastRow = len(ws_1['A'])
if lastRow >= start_row:
# load excel_file2
wb_2 = load_workbook(d_file)
ws_2 = wb_2.active
# lấy và ghi dữ liệu
res = []
for i in range(start_row, lastRow + 1):
scode = (ws_1.cell(row = i, column = 2).value)
if scode is not None:
for k in range(1, last_column + 1):
value_ = ws_1.cell(row = i, column = k).value
res.append(value_)
ws_2.append(res)
res.clear()
# lưu file excel_file2
wb_2.save(d_file)
print("Done!")
""" thực hiện sao chép dữ liệu
start_row = 8
last_column = 18 """
Read_Write(8, 18)
Tải file dưới, giải nén và mở file read_write_data.py bằng IDLE của Python rồi nhấn F5..
(Đừng bất ngờ về tốc độ đọc và ghi dữ liệu).
