【问题标题】:Edit table programmatically to fit content以编程方式编辑表格以适应内容
【发布时间】:2017-02-21 00:35:06
【问题描述】:

可以从 CSV 文件创建 HTML 页面,其中包含以下内容:

import pandas as pd

df = pd.read_csv('../data.csv',delimiter=';', engine='python')
df.to_html('csv.html')

此表的列宽似乎尊重标题(列标题)大小,但对于某些列,内容大于列标题并被换行到下一行。对于多字单元格 (aaaaaaaaa aaaaaaaaa),以下 CSV 会发生这种情况:

Name1;Name2;Name3;Name4;Name5
1;aaaaaaaaa aaaaaaaaa;b;aaaaaaaaa aaaaaaaaa;aaaaaaaaa aaaaaaaaa
2;aaaaaaaaa aaaaaaaaa;b;aaaaaaaaa aaaaaaaaa;aaaaaaaaa aaaaaaaaa
3;aaaaaaaaa aaaaaaaaa;b;aaaaaaaaa aaaaaaaaa;aaaaaaaaa aaaaaaaaa

我想让列的宽度足够大以适应内容(避免自动换行)。如何以编程方式(使用 Python)到达那里?

【问题讨论】:

  • 看来td { text-align: center; white-space:nowrap } 确实如此。

标签: python html css python-2.7 pandas


【解决方案1】:

答案基于this

import pandas as pd

filename = 'csv.html'

df = pd.read_csv('../data.csv',delimiter=';', engine='python')

html_begin = '\
<meta charset="UTF-8">\n\
<html>\n\
<head><link rel="stylesheet" type="text/css" href="csv.css"></head>\n\
<body>\n\n'

html_end = '\n\
</body>\n\
</html>\n'

with open(filename, 'w') as f:   
    f.write(html_begin)
    df.to_html(f)
    f.write(html_end)

csv.css 就像:

table {
    border: .5px solid lightgray;
    border-collapse: collapse;
    width: 100%;
}
th {
    border: .5px solid lightgray;
    text-align: center;
}
td {
    border: .5px solid lightgray;
    text-align: center;
    white-space:nowrap
}

或者(我会说一个更好的选择),可以避免 CSS 需求并通过Pandas Style 做所有事情,例如:

import pandas as pd

filename = 'csv_style.html'

df = pd.read_csv('../data.csv',delimiter=';', engine='python')

style =  df.style
style.set_properties(**{'text-align': 'center',
                       'white-space': 'nowrap'})

with open(filename, 'w') as f:  
    f.write(style.render())

【讨论】:

  • 您可能需要检查 Pandas Style formatting 以便按照 Pandas 的方式进行操作。 This 可能也很有趣...
  • 熊猫风格很酷!有趣的是,它对这个问题的问题没有帮助(或者我不知道如何使用 Pandas Style 来解决这个特定问题)。
  • 已编辑问题以包含一个 CSV 来说明问题(您需要缩小浏览器窗口以查看自动换行)。
  • 糟糕...我的错!现在我看到了如何用style.set_properties(**{'text-align': 'center', 'white-space': 'nowrap'}) 替换CSS 需求。熊猫风格干得好!
  • 所以更新你的答案是有意义的...... ;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多