简体   繁体   English

使用 xlsxwriter 更改要导出的数据类型

[英]Changing data type to export using xlsxwriter

So, I've been fighting with what I believe should be a simple problem for the last hour and a half.所以,在过去的一个半小时里,我一直在与我认为应该是一个简单的问题作斗争。 Essentially, I'm building a list scraped from a website that involves both Names as well as numbers.从本质上讲,我正在构建一个从网站上抓取的列表,其中包含名称和数字。 While scraping them they are stored into a string list.在抓取它们时,它们被存储到一个字符串列表中。 I'm using xlsxwriter in order to build a multisheet workbook with data from multiple webpages.我正在使用 xlsxwriter 来构建一个包含来自多个网页的数据的多表工作簿。 I can't seem to isolate the list items with "numbers" in them and convert them to a floating point.我似乎无法将其中包含“数字”的列表项隔离出来并将它们转换为浮点数。 I just started learning Python yesterday so it's very possible I'm just missing something small.我昨天刚开始学习 Python 所以很可能我只是错过了一些小东西。 I want the numbers to export to the excel sheet as numbers so that they are easier to work with.我希望将数字作为数字导出到 excel 工作表,以便更容易使用。

I essentially want to differentiate between actual text strings and number strings and convert the strings that contain numbers into floating points.我本质上想区分实际的文本字符串和数字字符串,并将包含数字的字符串转换为浮点数。 What I've attempted so far is isolating the first character using x[0], x[:0] and x[:1] to test it in an if statement shown below.到目前为止,我尝试的是使用 x[0]、x[:0] 和 x[:1] 隔离第一个字符,以便在下面显示的if语句中对其进行测试。 But when I get to that stage of the code while debugging, it is not actually converting it into a floating point number.但是当我在调试时进入代码的那个阶段时,它实际上并没有将其转换为浮点数。

# Function to check if string is number and convert
def checknum(x):
    y = x
    x = x[:1]
    if x in ['0','1','2','3','4','5','6','7','8','9','0']:
        x = float(x)
        return x
    else:
        return y

# How it's being used in my main program
row = 1
col = 0
for tr in soup.findAll('tr'):
    stats = []
    for td in tr.findAll('td'):
        stats.append(td.text)
    if stats:
        col = 0
        for item in stats:
            checknum(item)
            if isinstance(item, float):
                worksheet.write_number(row, col, item)
            else:
                worksheet.write(row, col, item)
            col += 1
        row += 1

One easy way to do this with XlsxWriter is to use the strings_to_number constuctor option.使用 XlsxWriter 执行此操作的一种简单方法是使用strings_to_number构造函数选项。 From the XlsxWriter docs :来自 XlsxWriter文档

strings_to_numbers : Enable the worksheet.write() method to convert strings to numbers, where possible, using float() in order to avoid an Excel warning about "Numbers Stored as Text". strings_to_numbers :启用worksheet.write()方法,在可能的情况下使用float()将字符串转换为数字,以避免出现有关“数字存储为文本”的 Excel 警告。 The default is False.默认值为假。 To enable this option use:要启用此选项,请使用:

workbook = xlsxwriter.Workbook(filename, {'strings_to_numbers': True})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM