Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/324.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用python将文本文件添加到现有Excel工作簿_Python_Excel_Formatting_Xlrd_Openpyxl - Fatal编程技术网

使用python将文本文件添加到现有Excel工作簿

使用python将文本文件添加到现有Excel工作簿,python,excel,formatting,xlrd,openpyxl,Python,Excel,Formatting,Xlrd,Openpyxl,如果这是一个基本问题,我深表歉意,但假设我有一个名为file.txt的制表符分隔文件,格式如下: Label-A [tab] Value-1 Label-B [tab] Value-2 Label-C [tab] Value-3 [...] Label-i [tab] Value-n 我希望或将此数据添加到文件workbook.xlsx中名为worksheet的excel工作表中,以便单元格包含以下值。我不想影响工作簿.xlsx中除受影响

如果这是一个基本问题,我深表歉意,但假设我有一个名为
file.txt
的制表符分隔文件,格式如下:

Label-A    [tab]    Value-1

Label-B    [tab]    Value-2

Label-C    [tab]    Value-3

[...]

Label-i    [tab]    Value-n
我希望或将此数据添加到文件
workbook.xlsx
中名为
worksheet
的excel工作表中,以便单元格包含以下值。我不想影响
工作簿.xlsx
中除受影响的两列以外的任何其他部分的内容

A1=Label-A

B1=Value-1

A2=Label-B

B2=Value-2

[etc.]
编辑:解决方案

import sys
import csv
import openpyxl

tab_file = sys.stdin.readlines()

reader = csv.reader(tab_file, delimiter='\t')
first_row = next(reader)
num_cols = len(first_row)

try:
    workbook = sys.argv[1]
    write_sheet = sys.argv[2]
except Exception:
    raise sys.exit("ERROR")

try:   
    first_col = int(sys.argv[3])
except Exception:
    first_col = 0

tab_reader = csv.reader(tab_file, delimiter='\t')
xls_book = openpyxl.load_workbook(filename=workbook)
sheet_names = xls_book.get_sheet_names()
xls_sheet = xls_book.get_sheet_by_name(write_sheet)
for row_index, row in enumerate(tab_reader):
    number = 0
    col_number = first_col
    while number < num_cols:
        cell_tmp = xls_sheet.cell(row = row_index, column = col_number)
        cell_tmp.value = row[number]
        number += 1
        col_number += 1
xls_book.save(workbook)
导入系统 导入csv 导入openpyxl tab_file=sys.stdin.readlines() reader=csv.reader(制表符文件,分隔符='\t') 第一行=下一行(读卡器) num\u cols=len(第一行) 尝试: 工作簿=sys.argv[1] write_sheet=sys.argv[2] 除例外情况外: 提升系统退出(“错误”) 尝试: 第一列=int(sys.argv[3]) 除例外情况外: 第一列=0 tab_reader=csv.reader(tab_文件,分隔符='\t') xls\u book=openpyxl.load\u工作簿(文件名=工作簿) 工作表名称=xls\u book.get\u工作表名称() xls\u sheet=xls\u book。按名称获取工作表(写工作表) 对于行索引,枚举中的行(选项卡读取器): 数字=0 列数=第一列 当数量这是VBA的工作,但如果我必须用Python来做,我会这样做:

import Excel
xl = Excel.ExcelApp(False)
wb = xl.app.Workbooks("MyWorkBook.xlsx")
wb.Sheets("Ass'y").Cells(1, 1).Value2 = "something"
wb.Save()
import win32com.client

class ExcelApp(object):
    def __init__(self, createNewInstance, visible = False):
        self._createNewInstance=createNewInstance

        if createNewInstance:
            self.app = win32com.client.Dispatch('Excel.Application')
            if visible:
                self.app.Visible = True
        else:
            self.app = win32com.client.GetActiveObject("Excel.Application")

    def __exit__(self):
        if self.app and self._createNewInstance:
            self.app.Quit()

    def __del__(self):
        if self.app and self._createNewInstance:
            self.app.Quit()

    def quit(self):
        if self.app:
            self.app.Quit()
from openpyxl import load_workbook
wb = load_workbook('workbook.xlsx')
ws = wb[sheetname]
for idx, line in enumerate(csvfile):
    ws.cell(row=idx, column=0) = line[0]
    ws.cell(row=idx, column=1) = line[1]
wb.save("changed.xlsx")
使用这样的帮助器
Excel.py
类:

import Excel
xl = Excel.ExcelApp(False)
wb = xl.app.Workbooks("MyWorkBook.xlsx")
wb.Sheets("Ass'y").Cells(1, 1).Value2 = "something"
wb.Save()
import win32com.client

class ExcelApp(object):
    def __init__(self, createNewInstance, visible = False):
        self._createNewInstance=createNewInstance

        if createNewInstance:
            self.app = win32com.client.Dispatch('Excel.Application')
            if visible:
                self.app.Visible = True
        else:
            self.app = win32com.client.GetActiveObject("Excel.Application")

    def __exit__(self):
        if self.app and self._createNewInstance:
            self.app.Quit()

    def __del__(self):
        if self.app and self._createNewInstance:
            self.app.Quit()

    def quit(self):
        if self.app:
            self.app.Quit()
from openpyxl import load_workbook
wb = load_workbook('workbook.xlsx')
ws = wb[sheetname]
for idx, line in enumerate(csvfile):
    ws.cell(row=idx, column=0) = line[0]
    ws.cell(row=idx, column=1) = line[1]
wb.save("changed.xlsx")

既然你说你已经习惯了在Bash中工作,我假设你正在使用某种Unix/Linux,那么这里有一些可以在Linux上工作的东西

在粘贴代码之前,我想指出几点:

在Unix(和Python)中使用Excel并不是那么简单。例如,您不能同时打开Excel工作表进行读写(至少,据我所知不是这样,尽管我必须承认我从未使用过
openpyxl
模块)。在处理Excel工作表时,Python有两个众所周知的模块(我习惯于使用它们):-D:一个用于读取Excel工作表(),另一个用于编写Excel工作表()。如果您想修改现有工作表,正如我所知,您需要阅读现有工作表,将其复制到可写工作表并编辑该工作表。检查问题/答案,并进行更详细的解释

多亏了这个模块,读取任何分隔的文件都要容易得多(它为逗号分隔的文件做好了准备,但也可以轻松地为其他分隔符进行调整)。看看吧

另外,从您的示例中,我不太确定制表符分隔文件的内容是否以某种方式指示Excel工作表上的行索引,或者它们纯粹是位置索引。当您说在选项卡分隔的文件中有
Value-2
,我不确定
2
是指Excel文件上的第二行,还是只是一些文本的示例。我假设是最新的(这更容易处理),因此,选项卡分隔文件第一行上显示的任何对标签值都将是Excel文件第一行上的第一对。如果不是这样,请留下评论a我们将处理它;-)

好,让我们假设以下场景:

您有一个选项卡分隔的文件,如下所示:

import Excel
xl = Excel.ExcelApp(False)
wb = xl.app.Workbooks("MyWorkBook.xlsx")
wb.Sheets("Ass'y").Cells(1, 1).Value2 = "something"
wb.Save()
import win32com.client

class ExcelApp(object):
    def __init__(self, createNewInstance, visible = False):
        self._createNewInstance=createNewInstance

        if createNewInstance:
            self.app = win32com.client.Dispatch('Excel.Application')
            if visible:
                self.app.Visible = True
        else:
            self.app = win32com.client.GetActiveObject("Excel.Application")

    def __exit__(self):
        if self.app and self._createNewInstance:
            self.app.Quit()

    def __del__(self):
        if self.app and self._createNewInstance:
            self.app.Quit()

    def quit(self):
        if self.app:
            self.app.Quit()
from openpyxl import load_workbook
wb = load_workbook('workbook.xlsx')
ws = wb[sheetname]
for idx, line in enumerate(csvfile):
    ws.cell(row=idx, column=0) = line[0]
    ws.cell(row=idx, column=1) = line[1]
wb.save("changed.xlsx")
stack37.txt:

要修改的excel文件是stack37.xls。它只有一个工作表(或者更好地说,您要修改的工作表是文件中的第一个工作表),最初看起来是这样的(在LibreOffice Calc中):

现在,这是python代码(我将其存储在一个名为stack37.py的文件中,它位于制表符分隔文件和excel文件的同一目录中):

运行此代码后,文件stack37.xls将如下所示:

import Excel
xl = Excel.ExcelApp(False)
wb = xl.app.Workbooks("MyWorkBook.xlsx")
wb.Sheets("Ass'y").Cells(1, 1).Value2 = "something"
wb.Save()
import win32com.client

class ExcelApp(object):
    def __init__(self, createNewInstance, visible = False):
        self._createNewInstance=createNewInstance

        if createNewInstance:
            self.app = win32com.client.Dispatch('Excel.Application')
            if visible:
                self.app.Visible = True
        else:
            self.app = win32com.client.GetActiveObject("Excel.Application")

    def __exit__(self):
        if self.app and self._createNewInstance:
            self.app.Quit()

    def __del__(self):
        if self.app and self._createNewInstance:
            self.app.Quit()

    def quit(self):
        if self.app:
            self.app.Quit()
from openpyxl import load_workbook
wb = load_workbook('workbook.xlsx')
ws = wb[sheetname]
for idx, line in enumerate(csvfile):
    ws.cell(row=idx, column=0) = line[0]
    ws.cell(row=idx, column=1) = line[1]
wb.save("changed.xlsx")

我的意思是不知道您到底想对选项卡分隔文件中的值做什么,不管您在其中为项目命名什么,它都会修改excel工作表的第一行,然后修改第二行。。。(即使您的第一个
被称为
Value-2
,上面的代码也不会将该值放在Excel工作表的第二行,而是放在第一行)它只是假设以制表符分隔的文件中的第一行与Excel工作表第一行上要设置的值相对应

让我们用一个稍加修改的例子来解释:

假设您的原始Excel文件看起来像我屏幕截图上的原始Excel文件(完整的
| Hello Ax | Bx |
),但您的制表符分隔文件现在看起来像这样:

import Excel
xl = Excel.ExcelApp(False)
wb = xl.app.Workbooks("MyWorkBook.xlsx")
wb.Sheets("Ass'y").Cells(1, 1).Value2 = "something"
wb.Save()
import win32com.client

class ExcelApp(object):
    def __init__(self, createNewInstance, visible = False):
        self._createNewInstance=createNewInstance

        if createNewInstance:
            self.app = win32com.client.Dispatch('Excel.Application')
            if visible:
                self.app.Visible = True
        else:
            self.app = win32com.client.GetActiveObject("Excel.Application")

    def __exit__(self):
        if self.app and self._createNewInstance:
            self.app.Quit()

    def __del__(self):
        if self.app and self._createNewInstance:
            self.app.Quit()

    def quit(self):
        if self.app:
            self.app.Quit()
from openpyxl import load_workbook
wb = load_workbook('workbook.xlsx')
ws = wb[sheetname]
for idx, line in enumerate(csvfile):
    ws.cell(row=idx, column=0) = line[0]
    ws.cell(row=idx, column=1) = line[1]
wb.save("changed.xlsx")
stack37.txt:

运行stack37.py后,Excel的外观如下所示:

(请参见?制表符分隔文件的第一行转到Excel文件的第一行)

更新1

我正在自己尝试
openpyxl
模块。。。理论上(根据文档),以下应该可以工作(注意,我已经将扩展更改为Excel2007/2010
.xlsx
):


但是如果我这样做,我的LibreOffice会拒绝打开新生成的文件
stack37\u new.xlsx
(可能是因为我的LibreOffice很旧?我在Ubuntu 12.04,LibreOffice版本3.5.7.2…谁知道呢,可能就是这样)

你应该使用标准库中的CSV模块来读取文件

在openpyxl中,您可以有如下内容:

import Excel
xl = Excel.ExcelApp(False)
wb = xl.app.Workbooks("MyWorkBook.xlsx")
wb.Sheets("Ass'y").Cells(1, 1).Value2 = "something"
wb.Save()
import win32com.client

class ExcelApp(object):
    def __init__(self, createNewInstance, visible = False):
        self._createNewInstance=createNewInstance

        if createNewInstance:
            self.app = win32com.client.Dispatch('Excel.Application')
            if visible:
                self.app.Visible = True
        else:
            self.app = win32com.client.GetActiveObject("Excel.Application")

    def __exit__(self):
        if self.app and self._createNewInstance:
            self.app.Quit()

    def __del__(self):
        if self.app and self._createNewInstance:
            self.app.Quit()

    def quit(self):
        if self.app:
            self.app.Quit()
from openpyxl import load_workbook
wb = load_workbook('workbook.xlsx')
ws = wb[sheetname]
for idx, line in enumerate(csvfile):
    ws.cell(row=idx, column=0) = line[0]
    ws.cell(row=idx, column=1) = line[1]
wb.save("changed.xlsx")

这不是最基本的,但是你应该在你自己尝试做的事情上表现出一些努力。这样的话,想要回答这个问题的人就会有办法(否则你也有可能被否决)谢谢你的建议。我已经添加了我所做的,但是这是我第一次使用Python(通常在Bash中工作),所以我不确定它对读者有多大帮助。如果您没有设置use_iterators=True,那么您可以修改现有文件。对于堆栈溢出,还有一个(稍微)建议:您不需要