将多个工作簿合并为一个

时间:2018-06-19 15:34:07

标签: excel python-2.7 openpyxl

我有各种各样的输入.xlsx文档,其中包含12张纸(每个.xlsx文档中所有纸页的名称都相同)。我需要将这些文件合并到一个.xlsx文档中,同时保留原始工作表的名称,但是每张工作表的所有文档中的数据都会附加到原始工作表中。

例如,请参阅我的原始输出:

Original Output

Desired Output

当前,我没有在任何地方添加inputFile名称,而只是试图合并到一个工作簿中。但是,我一直收到错误消息:

error

def createEmptyWorkbook(self, outputFileName):
    logging.info('creating empty workbook: %s' % (outputFileName))
    # create empty workbook
    ncoa_combined_report = openpyxl.Workbook()

    # save new file
    ncoa_combined_report.save(outputFileName)

    ncoa_combined_report = openpyxl.load_workbook(filename=outputFileName)#, data_only=True)

    return ncoa_combined_report

def combine_sheets(self, inputFiles):
    logging.info('combining ncoa reports to one workbook')

    # new output files
    outputFile = os.path.join(self.processingDir, 'combined_ncoa_report.xlsx')

    # create empty workbook
    ncoa_combined_report = self.createEmptyWorkbook(outputFile)

    # get a list of sheet names created in output file
    outputSheetNames = ncoa_combined_report.sheetnames

    for inputFile in inputFiles:
        logging.info('reading ncoa report: %s' % (os.path.split(inputFile)[-1]))
        # load entire input file into memory
        input_wb = openpyxl.load_workbook(filename = inputFile)#, data_only=True)

        # get sheet name values in inputFile 
        sheets = input_wb.sheetnames

        # iterate worksheets in input file
        for worksheet in input_wb.worksheets:
            outputSheetMaxRow = 0
            currentSheet = ''
            row = ''
            column = ''

            logging.info('working on sheet: %s' % (worksheet.title))
            # check if sheet exist in output file and add if neccissary
            if not worksheet.title in outputSheetNames:
                logging.info('creating sheet: %s' % (worksheet.title))
                currentSheet = ncoa_combined_report.create_sheet(worksheet.title)
            else:
                currentSheet = worksheet.title

            ## check if default sheet name is in output
            #if 'Sheet' in outputSheetNames:
            #    ncoa_combined_report.remove_sheet(ncoa_combined_report.get_sheet_by_name('Sheet'))

            outputSheetMaxRow = currentSheet.max_row

            for row, entry in enumerate(worksheet, start=1):
                logging.info('working on row: %s' % (row))
                for cell in entry:
                    try:
                        outputSheetMaxRow = currentSheet.max_row
                        # add cell value to output file
                        #currentSheet[cell.coordinate].value
                        currentSheet.cell(row=row+outputSheetMaxRow, column=cell.column).value = cell.value #, value=cell
                    except:
                        logging.critical('could not add row:%s, cell:%s' % (row, entry))
                        raise ValueError('could not add row:%s, cell:%s' % (row, entry))

        # save new file
        ncoa_combined_report.save(outputFile)

我不确定为什么会收到错误或需要更新以纠正错误。任何指导表示赞赏。

1 个答案:

答案 0 :(得分:0)

我认为我发现了这部分代码的问题。我找到了可以从openpyxl.utils获取xy,col和row的位置,这使我可以在附加位置的正确位置插入。希望这会在将来对其他人有所帮助。

$.ajax({
type: "GET",
url: "/Receiving/GetUnorderedParts",
datatype: "html",
data: { "id": button.attr("data-ponumber") },
success: function(data) {
    var orderButton = $(".js-Order");
    orderButton.removeClass("invisible");
    tbl = $("#UnorderedDetail")
        .DataTable({
            "destroy": true,
            "searching": false,
            "ordering": false,
            "lengthChange": false,
            "pagingType": "full_numbers",
            "paging": true,
            "lengthMenu": [10, 25, 50, 75, 100],
            ajax: {
                url: "/Receiving/GetUnorderedParts",
                data: { "id": button.attr("data-ponumber") },
                datasrc: ""
            },
            "columnDefs": [
                {
                    targets: -1,
                    className: 'dt-body-center'
                }
            ],
            columns: [
                {
                    data: "Description"
                },
                {
                    data: "VendorPartNumber"
                },
                {
                    data: "Quantity"
                },
                {
                    data: "CartID",
                    render: function(data) {
                        return "<button class='btn btn-danger js-delete' data-cart-id=" +
                            data +
                            ">Delete</button>";
                    }
                }
            ] //EOColumns
        }); //EODataTable

} //EOSuccess