写入 CSV 会丢失 excel 格式。
Writing into CSV loses the excel formatting.
我正在尝试格式化 excel sheet 并将其写入 CSV 文件。我可以使用 openpyxl 格式化文件,但是,当我将其写入 CSV 文件时,格式会丢失。 excel sheet 有 2 个值,日期“25-Sept-2017”和 pi 值“3.14159265359”。格式化excelsheet后,excelsheet中的值为“2017-09-25”和“3.14”。但在写入 CSV 文件后,CSV 的值是“2017-09-25 00:00:00”和“3.14159265359”
import openpyxl, csv
try:
wb = openpyxl.load_workbook("./Decimals.xlsx", data_only="True")
sheet = wb.active
for r in sheet.rows:
r[0].number_format = "YYYY-MM-DD"
r[1].number_format = "0.00"
wb.save("Decimals.xlsx")
except Exception as e:
print(e)
with open('trialCSV.csv', 'w', newline='') as csvFile:
c = csv.writer(csvFile)
for r in sheet.rows:
c.writerow([cell.value for cell in r])
我搜索过类似的问题,但没有找到。我一直在尝试为此找到解决方案 2 天,但没有运气。任何帮助是极大的赞赏!谢谢你。
CSV 当然没有格式化的概念,只有数据。 Excel 格式更改数据的显示而不更改基础数据本身(否则,例如,一旦您将数据从“0.000000”格式更改为“0.000”,您将永远无法返回)。
如果您确实希望格式为 "stick",您将需要操作数据本身(在您的示例中,通过将日期转换为您想要的格式的字符串,然后四舍五入pi 的值),而不是格式。
我正在尝试格式化 excel sheet 并将其写入 CSV 文件。我可以使用 openpyxl 格式化文件,但是,当我将其写入 CSV 文件时,格式会丢失。 excel sheet 有 2 个值,日期“25-Sept-2017”和 pi 值“3.14159265359”。格式化excelsheet后,excelsheet中的值为“2017-09-25”和“3.14”。但在写入 CSV 文件后,CSV 的值是“2017-09-25 00:00:00”和“3.14159265359”
import openpyxl, csv
try:
wb = openpyxl.load_workbook("./Decimals.xlsx", data_only="True")
sheet = wb.active
for r in sheet.rows:
r[0].number_format = "YYYY-MM-DD"
r[1].number_format = "0.00"
wb.save("Decimals.xlsx")
except Exception as e:
print(e)
with open('trialCSV.csv', 'w', newline='') as csvFile:
c = csv.writer(csvFile)
for r in sheet.rows:
c.writerow([cell.value for cell in r])
我搜索过类似的问题,但没有找到。我一直在尝试为此找到解决方案 2 天,但没有运气。任何帮助是极大的赞赏!谢谢你。
CSV 当然没有格式化的概念,只有数据。 Excel 格式更改数据的显示而不更改基础数据本身(否则,例如,一旦您将数据从“0.000000”格式更改为“0.000”,您将永远无法返回)。
如果您确实希望格式为 "stick",您将需要操作数据本身(在您的示例中,通过将日期转换为您想要的格式的字符串,然后四舍五入pi 的值),而不是格式。