Created
May 7, 2019 06:56
-
-
Save hanminghui/539e8a8d76eb5dd778ec508affd1c376 to your computer and use it in GitHub Desktop.
[dict_to_excel] write python dict to excel using pandas #pandas #excel
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import pandas as pd | |
| import xlsxwriter | |
| # an example dict | |
| table_result = [] | |
| table_row = {} | |
| element = 3.14 | |
| table_row['col_1'] = 1000 | |
| table_row['col_2'] = 3e-5 | |
| table_row['col_3'] = 2.242 | |
| table_row['col_4'] = "test" | |
| table_row['col_5'] = 'A' | |
| table_row['col_6'] = element | |
| table_row['col_7'] = 0.6336348684210527 | |
| table_result.append(table_row) | |
| print("table in python dict:") | |
| print(table_result) | |
| print("-------------------------------------------------------------------------------") | |
| col_names = ['col_1','col_2','col_3','col_4','col_5','col_6','col_7'] | |
| df = pd.DataFrame(table_result, columns=col_names) | |
| print("table in pandas dataframe:") | |
| print(df) | |
| print("==================================================") | |
| print("method1:") | |
| # method 1, use to_excel directly | |
| df.to_excel('table_result1.xlsx', engine='xlsxwriter') | |
| print("write to excel: table_result1.xlsx") | |
| # method 2, use a ExcelWriter to save | |
| print("==================================================") | |
| print("method2:") | |
| writer = pd.ExcelWriter('table_result2.xlsx', engine='xlsxwriter') | |
| df.to_excel(writer, sheet_name='Sheet1') | |
| # some modify in writer(the excel file) | |
| print("some manipulation") | |
| # Get the xlsxwriter objects from the dataframe writer object. | |
| # you can use it to manipulate the excel, | |
| # for example, change a value, or add a photo, a chart, and formatting | |
| # more information to check XlsxWriter | |
| workbook = writer.book | |
| worksheet = writer.sheets['Sheet1'] | |
| # Add a bold format to use to highlight cells. | |
| bold = workbook.add_format({'bold': True}) | |
| worksheet.write('F2', 'Manipulation', bold) | |
| writer.save() | |
| print("write to excel: table_result2.xlsx") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment