有没有办法用Python的xlsxwriter自动调整评论窗口高度?

问题描述 投票:0回答:1

我刚刚实现了一种方法,将各种元数据附加到我们在科学数据 django 应用程序的数据验证界面中生成的 Excel 文件中的单元格。我基本上正在放弃使用谷歌表格。

谷歌表格更擅长的一件事是显示评论。无论评论的内容是什么,评论悬停窗口都会自动适应评论的大小。我不太使用 Excel,所以当我第一次查看单元格上附加的注释时,我感到很沮丧。所有评论窗口的大小相同,并且根据换行符,甚至没有任何迹象表明任何内容被截断。

有没有人找到一种方法来至少自动调整高度?我查看了文档,但找不到。更改高度的方法是通过 height 或 y_scale 选项,但这些都没有考虑内容。它只需要任意数值。

自动调整之所以有利,是因为评论内容是通过编程生成的,并且会随着文件的不同而变化:有时文本很小,有时文本很大。

其他希望能够解决的烦恼:

  • 有没有办法选择单元格中出现的三角形的颜色?我想区分错误和无害的评论。
  • 有没有办法让您将鼠标悬停在评论窗口本身上时保留评论并使文本可选择,而不必先单击以显示评论?

无需手动显示和调整评论窗口尺寸:

调整评论窗口后:

python excel xlsxwriter
1个回答
0
投票

有没有人找到一种方法来至少自动调整高度?

文件格式中没有任何内容可以自动调整评论的高度。您需要根据字符串长度和绕行进行一些估计。准确的计算需要考虑字体指标。

有没有办法选择单元格中出现的三角形的颜色?我想区分错误和无害的评论。

我不这么认为。这是 Excel 的固定属性。

有没有办法让您将鼠标悬停在评论窗口本身上时保留评论并使文本可选择,而不必先单击以显示评论?

您可以为每个评论设置

visble
属性或使用工作表
show_comments()
方法。

下面的示例显示了其中一些选项和解决方法:

import textwrap
import xlsxwriter

comment1 = """The unique name of the biological sample.

MUST match the sample names in the peak annotation
file, minus any appended suffixes.
"""

comment2 = """The date the sample was collected.

Format: YYYY-MM-DD.
"""


# Approximate esitmate of the number of lines in a wrapped comment.
def count_wrapped_lines(comment):
    num_lines = 0
    segments = comment.splitlines()
    for segment in segments:
        if segment == "":
            num_lines += 1
        else:
            lines = textwrap.wrap(segment, width=30)
            num_lines += len(lines)

    if num_lines == 0:
        num_lines = 1

    return num_lines


# Map the number of lines to a pixel height.
def comment_height_in_pixels(comment):
    num_lines = count_wrapped_lines(comment)
    return num_lines * 16


# Create a new workbook and add a worksheet.
workbook = xlsxwriter.Workbook("comments.xlsx")
worksheet = workbook.add_worksheet()

# Write some comments.
worksheet.write("A1", "Sample")
worksheet.write_comment(
    "A1", comment1, {"height": comment_height_in_pixels(comment1), "y_offset": 150}
)

worksheet.write("B1", "Date")
worksheet.write_comment(
    "B1", comment2, {"height": comment_height_in_pixels(comment2), "y_offset": 50}
)


# Make all comments visible.
worksheet.show_comments()


workbook.close()

输出:

© www.soinside.com 2019 - 2024. All rights reserved.