Jac*_* B. 2 python csv format excel
我正在尝试编写一个函数,从我的数据库中获取数据,该函数已经正常工作。
这是我在添加实际记录之前的标题代码:
with open('csv_template.csv', 'a') as template_file:
#declares the variable template_writer ready for appending
template_writer = csv.writer(template_file, delimiter=',')
#appends the column names of the excel table prior to adding the actual physical data
template_writer.writerow(['Arrangement_ID','Quantity','Cost'])
#closes the file after appending
template_file.close()
Run Code Online (Sandbox Code Playgroud)
这是我的记录代码,它包含在 while 循环中,并且是将两个脚本分开的主要原因。
with open('csv_template.csv', 'a') as template_file:
#declares the variable template_writer ready for appending
template_writer = csv.writer(template_file, delimiter=',')
#appends the data of the current fetched values of the sql statement within the while loop to the csv file
template_writer.writerow([transactionWordData[0],transactionWordData[1],transactionWordData[2]])
#closes the file after appending
template_file.close()
Run Code Online (Sandbox Code Playgroud)
现在,一旦我为 excel 准备好这些数据,我就在 excel 中运行该文件,我希望它采用可以立即打印的格式,但是,当我打印时,excel 单元格的列宽太小并且导致它在打印过程中被切断。
我曾尝试更改 excel 中的默认列宽,并希望它能永久保留该格式,但似乎并非如此,每次我在 excel 中重新打开 csv 文件时,它似乎都完全重置回默认列宽。
这是我使用 python 在 excel 中打开 csv 文件的代码,注释是当我可以实际格式化准备打印的电子表格时要使用的实际代码。
#finds the os path of the csv file depending where it is in the file directories
file_path = os.path.abspath("csv_template.csv")
#opens the csv file in excel ready to print
os.startfile(file_path)
#os.startfile(file_path, 'print')
Run Code Online (Sandbox Code Playgroud)
如果有人对此有任何解决方案或想法,请告诉我。
小智 6
不幸的是,我认为这对于 CSV 文件格式是不可能的,因为它们只是纯文本逗号分隔值并且不支持格式。
我曾尝试更改 excel 中的默认列宽,但每次我在 excel 中重新打开 csv 文件时,它似乎都会重置回默认列宽。
如果在编辑后将文件保存为 excel 格式,则应该可以解决此问题。
或者,csv您可以使用该库xlsxwriter代替它,它允许您在代码中设置列的宽度。
请参阅https://xlsxwriter.readthedocs.io和https://xlsxwriter.readthedocs.io/worksheet.html#worksheet-set-column。
希望这可以帮助!
| 归档时间: |
|
| 查看次数: |
4846 次 |
| 最近记录: |