【问题标题】:xlsxwriter creating files that are unreadable (python)xlsxwriter 创建不可读的文件(python)
【发布时间】:2020-04-22 21:33:15
【问题描述】:

因此,我创建了一个程序,该程序通过将文档的单元格着色为与像素相同的颜色,将图像复制到 Excel 文档中。这是我的代码,

from PIL import Image
import xlsxwriter

image = xlsxwriter.Workbook('Image.xlsx')

image_sheet = image.add_worksheet()

with Image.open("11111.jpg") as px:
    cookie = px.load()
cookie2 = Image.open("11111.jpg")
image_pixels = 0
image_pixels_2 = 0
cookie_height = cookie2.height
cookie_width = cookie2.width
image_sheet.set_column(0, cookie_width, 2.14)

while image_pixels <= cookie_height - 1:
     print(image_pixels)
     while image_pixels_2 <= cookie_width - 1:
          rgb = '#%02x%02x%02x' % cookie[image_pixels_2, image_pixels]
          cell_format = image.add_format()
          cell_format.set_shrink()
          cell_format.set_bg_color(rgb)
          image_sheet.write(image_pixels, image_pixels_2, ' ', cell_format)
          image_pixels_2 += 1

     image_pixels += 1
     if image_pixels_2 >= cookie_width:
          image_pixels_2 = 0

image.close()

它会生成文件,但是当我打开 excel 文件时,它说它不可读并删除所有格式。我不确定为什么会这样。该文件有时是可读的,但有时不是。

【问题讨论】:

    标签: python python-3.x excel-2010 xlsxwriter


    【解决方案1】:

    Excel 有a limit of 64,000 unique formats in a file。 XlsxWriter 删除/替换重复格式,但您的程序可能超出 64k 格式限制。

    您可以通过像这样更改程序来打印所使用的唯一格式的数量来检查:

    unique = {}
    while image_pixels <= cookie_height - 1:
         print(image_pixels)
         while image_pixels_2 <= cookie_width - 1:
              rgb = '#%02x%02x%02x' % cookie[image_pixels_2, image_pixels]
              unique[rgb] = 1
              cell_format = image.add_format()
              cell_format.set_shrink()
              cell_format.set_bg_color(rgb)
              image_sheet.write(image_pixels, image_pixels_2, ' ', cell_format)
              image_pixels_2 += 1
    
         image_pixels += 1
         if image_pixels_2 >= cookie_width:
              image_pixels_2 = 0
    
    image.close()
    print('Unique fomats = ', len(unique))
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-27
      • 1970-01-01
      • 2016-05-28
      • 1970-01-01
      • 2022-10-16
      • 1970-01-01
      • 1970-01-01
      • 2019-07-23
      相关资源
      最近更新 更多