我正在尝试编写一个函数,从我的数据库中获取数据,该函数已经可以正常工作。
这是我在添加实际记录之前的标题代码:
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()
这是我的记录代码,包含在一个 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()
现在,一旦我为 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')
如果有人对此有任何解决方案或想法,请告诉我。
最佳答案
不幸的是,我认为这对于 CSV 文件格式是不可能的,因为它们只是纯文本逗号分隔值并且不支持格式化。
I have tried altering the default column width within excel but every time that I re-open the csv file in excel it seems to reset back to the default column width.
如果在编辑文件后将文件保存为 excel 格式,应该可以解决此问题。
或者,您可以使用 xlsxwriter
而不是使用 csv
库,它确实允许您设置您的列的宽度代码。
参见 https://xlsxwriter.readthedocs.io和 https://xlsxwriter.readthedocs.io/worksheet.html#worksheet-set-column .
希望这对您有所帮助!
关于python - 如何增加 csv 文件的默认列宽,以便在打开文件时所有文本都能正确显示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53380103/