Python uses xlwt, xlrd, xlutils to realize the function of reading and writing to the same Excel at the same time

    When using Python to process Excel files, you often encounter the task of reading the data of a certain cell, and obtaining new data after program processing, and want to insert the new data into the next column of the same Excel. I don't want to create a new Excel table, I just want to access and insert data on the same file.

    At this time, you can use the Excel toolkit modules xlwt, xlrd, and xlutils provided by Python to achieve the above functions.

    

import xlwt
import xlrd
from xlutils.copy import copy


class ExcelProcess:
    def __init__(self, doc_file, sheet_name):
        self.doc_file = doc_file
        self.sheet_name = sheet_name

    def get_rows_number(self):
        """
        获取某一table中数据的总行数
        :return: 数据的总行数
        """
        data = xlrd.open_workbook(self.doc_file)
        table = data.sheet_by_name(self.sheet_name)
        return table.nrows

    def excel_read(self, x, y):
        """
        读取Excel工作表中某一table的单元格的值
        :param x:
        :param y:
        :return: 单元格的值
        """
        data = xlrd.open_workbook(self.doc_file)
        table = data.sheet_by_name(self.sheet_name)
        return table.cell(x, y).value

    def excel_create(self, x, y, value):
        """
        创建一个Excel工作表
        :param x: 单元格横坐标
        :param y: 单元格纵坐标
        :param value: 要写入单元格的值
        :return:
        """
        data = xlwt.Workbook()
        table = data.add_sheet(self.sheet_name)
        table.write(x, y, value)
        data.save(self.doc_file)

    def excel_change(self, x, y, value):
        """
        修改原始excel文件
        :param x: 单元格横坐标
        :param y: 单元格纵坐标
        :param value: 要写入单元格的值
        :return:
        """
        rb = xlrd.open_workbook(self.doc_file)
        # 管道作用
        wb = copy(rb)
        # 通过get_sheet()获取的sheet有write()方法
        # ws = wb.get_sheet(0)  # 1代表是写到第几个工作表里,从0开始算是第一个。
        ws = wb.sheet_by_name(self.sheet_name)
        ws.write(x, y, value)
        wb.save(self.doc_file)

    Wrote a tool class for Excel processing, used to create Excel worksheet (excel_create function), read Excel worksheet (excel_read function), modify Excel worksheet (excel_change function) and get data rows of Excel worksheet Number (get_rows_number function) function.

    Among them, the excel_change function mainly uses a pipeline to achieve simultaneous reading and writing tasks, using the copy function provided in the xlutils toolkit, and then writing the copy table into new data to overwrite the original work table.

Guess you like

Origin blog.csdn.net/qq_22472047/article/details/104838945