xlsxwriter 创建不可读的文件 (python)

xlsxwriter creating files that are unreadable (python)

所以我创建了一个程序,通过将文档的单元格着色为与像素相同的颜色,将其复制到 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 文件时,它说它不可读并删除了所有格式。我不确定为什么会这样。该文件有时可读,但有时不可读。

Excel 有 a limit of 64,000 unique formats in a file。 XlsxWriter removes/replaces 重复格式,但您的程序可能超出了 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))