我想首先显示一个适用于XLSX的示例(但不幸的是,我需要XLS,而该方法对此不起作用)。只是为了澄清一下,我的主要问题是生成的XLS文件的列类型格式。
# Method that works for XLSX import pandas as pd # Example Dataframe df = pd.DataFrame({'Numbers': [1000, 2000, 3000, 4000, 5000], 'Names': ['Adam','Blake','Chad','Drake','Erak'], 'Weights': [1.05, 2.10, 3.15, 4.20, 5.25], }) # Create a Pandas Excel writer writer = pd.ExcelWriter(r'c:\users\3619678\desktop\example_file.xlsx') # Convert the dataframe to an Excel object df.to_excel(writer, sheet_name='Sheet1', index=False) # Get the xlsxwriter workbook and worksheet objects workbook = writer.book worksheet = writer.sheets['Sheet1'] # Define cell formats number_format = workbook.add_format({'num_format': '0.00'}) # Set a certain column's width and apply certain format worksheet.set_column('A:A', 20, number_format) # Close the Pandas Excel writer and output the Excel file. writer.save()
现在这是我到目前为止对XLS版本最接近的尝试:
import pandas as pd # Example Dataframe df = pd.DataFrame({'Numbers': [1000, 2000, 3000, 4000, 5000], 'Names': ['Adam','Blake','Chad','Drake','Erak'], 'Weights': [1.05, 2.10, 3.15, 4.20, 5.25], }) import xlwt # Create a workbook and add a worksheet workbook = xlwt.Workbook(r'c:\users\3619678\desktop\example_file.xls') worksheet = workbook.add_sheet('sheet1',cell_overwrite_ok=True) # Create formats number_format = xlwt.easyxf(num_format_str='0.00') # Iterate over the data and write it out row by row for x, y in df.iterrows(): for z, value in enumerate(y): worksheet.write(x, z, value, number_format) # Save/output the workbook workbook.save(r'c:\users\3619678\desktop\example_file.xls')
但是,此版本的问题在于,它不仅不显示标题,而且还对所有单元格应用了格式。如果有人能帮助我,我将不胜感激,我为此付出了永远!
我想首先显示一个适用于XLSX的示例(但不幸的是,我需要XLS,而该方法对此不起作用)。再次说明一下,我的主要问题是列类型...
使用df.to_excel应该容易得多