使用xlwgins在Excel中编写一个没有相同列数的二维列表

时间:2017-07-13 00:38:24

标签: python excel xlwings

我正在尝试在Excel的工作簿中编写如下文本文件:

  

14807 2010    2 0“”-1 0 0
   0   接头    0   框架    3200    1 0 0 0 0“1”0“”0 0 .15 .9 0“”1.1 28 0 0 0 .3 .3 0
   1 0 0 0 0“2”0“”0 0 .15 .9 0“”1.1 28 0 0 0 .3 .3 0
   1 0 0 0 0“3”0“”0 0 .15 .9 0“”1.1 28 0 0 0 .3 .3 0
   1 0 0 0 0“1”0“”0 0 .15 .9 0“”1.1 28 0 0 0 .3 .3 0

这个想法是在不同的Cell中写下每个值。我怎样才能有效地做到这一点?我有这个,但不起作用:

import xlwings as xw

filename = "Viguetas de N+47.00 a N+145.80.dcc"
dc_cad = DC_CAD(filename)
dc_cad.show_data()

class DC_CAD:
    def __init__(self, filename):
        self.filename = filename
        self.data = self.getData()
        print(self.data[:5])

        self.excel_app = xw.App(visible = False, add_book = False, impl = None)  # impl ?
        self.wb = self.excel_app.books.add()
        self.sh = self.wb.sheets[0]
        self.sh.range("A1").value = self.data

    def getData(self):
        return [line.split(' ') for line in open(self.filename, 'r').read().split('\n')]

    def show_data(self):
        self.excel_app.visible = True

1 个答案:

答案 0 :(得分:0)

我找到了这个解决方案,但速度很慢:

class DC_CAD:
    def __init__(self, filename):
        self.filename = filename
        self.data = self.getData()

        self.excel_app = xw.App(visible = False, add_book = False, impl = None)  # impl ?
        self.wb = self.excel_app.books.add()
        self.sh = self.wb.sheets[0]
        rng = self.sh.range("A1")
        for i, line in enumerate(self.data[0:10]):
            rng.offset(i, 0).value = line

    def getData(self):
        return [' '.join(filter(None, line.split(' '))).split(' ') for line in open(self.filename, 'r').read().split('\n')]

    def show_data(self):
        self.excel_app.visible = True