从 CSV 列表到 XLSX。数字识别为文本而不是数字

From CSV list to XLSX. Numbers recognise as text not as numbers

我正在使用 CSV 数据文件。

我从这个文件中获取了一些具体数据。这些数据传送到一个包含单词字符串和数字的列表(保存为字符串,叹息!)。 像这样:

data_of_interest = ["string1", "string2, "242", "765", "string3", ...]

我创建了新的 XLSX(应该有这种格式)文件,其中粘贴了这些数据。 该脚本完成工作,但在新的 XLSX 文件中,数字(浮点数和整数)作为文本粘贴。 我可以在 excel 上手动转换它们的格式,但这会很耗时。

有没有办法在编写新的 XLSX 文件时自动执行此操作?

这里是我使用的代码摘录:

## import library and create excel file and the working sheet
import xlsxwriter
workbook = xlsxwriter.Workbook("newfile.xlsx")
sheet = workbook.add_worksheet('Sheet 1')

## take the data from the list (data_of_interest) from csv file
## paste them inside the excel file, in rows and columns
column = 0
row = 0
for value in data_of_interest:
    if type(value) is float:
        sheet.write_number(row, column, value)
    elif type(value) is int:
        sheet.write_number(row, column, value)
    else:
        sheet.write(row, column, value)
    column += 1
row += 1
column = 0
workbook.close()

问题是否与原始列表中的数字已经是 str 类型有关,因此代码无法识别它们是 floatint(等等它不会将它们写成数字)?

感谢您的帮助!

在 if 块之前尝试 int(value) 或 float(value)。

你读取的数据都是字符串,你必须先尝试将它们转换成float或int类型。

示例:

for value in data_of_interest:
    try:
        value.replace(',', '.') # Note that might change commas to dots in strings which are not numbers
        value = float(value)
    except ValueError:
        pass
    if type(value) is float:
        sheet.write_number(row, column, line)
    else:
        sheet.write(row, column, line)
    column += 1
row += 1
column = 0
workbook.close()

使用 XlsxWriter 执行此操作的最佳方法是使用 strings_to_numbers constructor 选项:


import xlsxwriter

workbook = xlsxwriter.Workbook("newfile.xlsx", {'strings_to_numbers': True})
sheet = workbook.add_worksheet('Sheet 1')

data_of_interest = ["string1", "string2", "242", "765", "string3"]

column = 0
row = 0

for value in data_of_interest:
    sheet.write(row, column, value)
    column += 1

workbook.close()

输出:(请注意,没有任何关于数字存储为字符串的警告):