1.先转两篇文章:
python读写Excel和读写Xml. https://linsir.org/post/read-and-write-excel-and-xml-files-with-python
用python读写Excel文件 http://www.gocalf.com/blog/python-read-write-excel.html
2.xlsxwriter的官方文档在这里:
https://xlsxwriter.readthedocs.io/
3.贴下我照抄别人的代码:
-
import xlsxwriter
-
-
workbook = xlsxwriter.Workbook("add_sheet.xlsx")
-
worksheet = workbook.add_worksheet(name="New Sheet 2")
-
expenses = (
-
["Rent", 1000],
-
["Gas", 100],
-
["Food", 300],
-
["Gym", 50],
-
)
-
-
row = 0
-
col = 0
-
for item,cost in (expenses):
-
worksheet.write(row, col, item)
-
worksheet.write(row, col+1, cost)
-
row += 1
-
worksheet.write(row, 0, 'Total')
-
worksheet.write(row, 1, '=SUM(B1:B4)')
-
-
format1 = workbook.add_format({"bg_color":"blue",
-
"font_color": "red"})
-
-
worksheet.conditional_format("B1:KB5",
-
{"type": "cell",
-
"criteria": ">=",
-
"value": 150,
-
"format": format1})
-
-
-
workbook.close()
效果如下: 我发现我的SUM公式没有算结果,显示为0,不知道为什么.我用的是libreoffice 5.3 .
下面是个有chart的例子,同样的公式仍然是没有计算出来结果.
-
import xlsxwriter
-
-
workbook = xlsxwriter.Workbook("chart_column.xlsx")
-
-
worksheet = workbook.add_worksheet()
-
chart = workbook.add_chart({"type" : "column"})
-
-
data = [
-
[ "Year", "2013", "2014", "2015" ],
-
[ "Revenue", 100, 120, 125 ],
-
[ "COGS", 80, 90, 70 ],
-
[ "Profit", 20, 30, 55 ],
-
]
-
-
worksheet.write_row("A1", data[0])
-
worksheet.write_row("A2", data[1])
-
worksheet.write_row("A3", data[2])
-
worksheet.write_row("A4", data[3])
-
-
chart.add_series({"values" :"=Sheet1!$B$2:$B$4","name":"2013"})
-
chart.add_series({"values" :"=Sheet1!$C$2:$C$4","name":"2014"})
-
chart.add_series({"values" :"=Sheet1!$D$2:$D$4","name":"2015"})
-
-
worksheet.insert_chart("G1", chart)
-
-
worksheet.write(5, 0, "% Gain")
-
worksheet.write(5, 1, "=(B4/B2)*100")
-
worksheet.write(5, 2, "=(C4/C2)*100")
-
worksheet.write(5, 3, "=(D4/D2)*100")
-
-
workbook.close()
结果如下:
阅读(1228) | 评论(0) | 转发(0) |