Python for Finance: Analyze Big Financial Data

(Elle) #1

This way, the sample data can be written “in bulk” to the two Worksheet objects:


In  [ 11 ]: for c in range(data.shape[ 0 ]):
for r in range(data.shape[ 1 ]):
ws_1.write(r, c, data[c, r])
ws_2.write(r, c, data[r, c])

The save method of the Workbook class allows us to save the whole Workbook object to


disk:


In  [ 12 ]: wb.save(path    +   ‘workbook.xls’)

On Windows systems, the path might look like r”C:\path\data\workbook.xls”.


Generating Workbooks (.xslx)


(The creation of spreadsheet files in the new format works essentially the same way. First,


we create a Workbook object:


In  [ 13 ]: wb  =   xlsxwriter.Workbook(path    +   ‘workbook.xlsx’)

Second, the Worksheet objects:


In  [ 14 ]: ws_1    =   wb.add_worksheet(‘first_sheet’)
ws_2 = wb.add_worksheet(‘second_sheet’)

Third, we write data to the Worksheet objects:


In  [ 15 ]: for c in range(data.shape[ 0 ]):
for r in range(data.shape[ 1 ]):
ws_1.write(r, c, data[c, r])
ws_2.write(r, c, data[r, c])

Fourth, we close the Workbook file object:


In  [ 16 ]: wb.close()
In [ 17 ]: ll $path*
Out[17]: -rw––- 1 yhilpisch 7375 Sep 28 18:18 data/chart.xlsx
-rw––- 1 yhilpisch 5632 Sep 28 18:18 data/workbook.xls
-rw––- 1 yhilpisch 6049 Sep 28 18:18 data/workbook.xlsx

If everything went well, the file opened in Microsoft Excel should look like Figure 12-1.

Free download pdf