How to convert strings to numbers, when taking data from .csv to .xlsx, using openpyxl

时间:2016-07-11 23:08:43

标签: python excel csv openpyxl

I wrote this code to take info I have stored inside a .csv file and put it into a .xlsx file. When it is in the excel doc all of the information are strings. I can't figure out a way to change them into numbers so I can then use openpyxl in order to create a line graph. Here is the code

import openpyxl
import csv

examplefile = open('output.csv')
exampleReader = csv.reader(examplefile)
exampleData = list(exampleReader)


wb = openpyxl.load_workbook('open.xlsx')
ws = wb.get_sheet_by_name('Sheet1')

for i in range (1,9):
    for h in range(1, 5):
        a = i-1
        b = h-1
        ws.cell(row=i, column=h).value = exampleData[a][b]


wb.save('practice.xlsx')

and here is the csv file

Date,Temp,Min Temp,Max Temp
2016-07-11,288.69,287.68,288.69
2016-07-12,289.55,288.79,289.55
2016-07-13,294.3,293.79,294.3
2016-07-14,296.35,296.098,296.35
2016-07-15,291.824,291.824,291.824
2016-07-16,293.373,293.373,293.373
2016-07-17,291.808,291.808,291.808

also I know that this is not the most efficient way to get the data from a to b, so if there are any recommendations on how to do that better, please include those.

1 个答案:

答案 0 :(得分:0)

The CSV reader reads the file into a 2D list, where each row represents a line. The data is read in and stored as strings. So you'd need to explicitely cast the values to the desired type, something like this:

ws.cell(row=i, column=h).value = float(exampleData[a][b])

Look here for further explanation: Python import csv to list