自动将多个Excel文件的单元格属性

时间:2019-06-17 07:27:52

标签: excel

我有大约100个Excel文件,其中K和L列表示为浮点,例如0.5677。我想将这些列表示为百分比,在这种情况下为56.8%。有没有办法可以使它自动化?显然,我可以手动调整列,但这很耗时。

我没有使用Macro或VBA的经验。

任何帮助将不胜感激。

亲切的问候,M。

1 个答案:

答案 0 :(得分:0)

我找到了使用Python Pandas实现此目的的有用方法。就我而言,熊猫还是Excel文件的来源。

import pandas as pd

# Create a Pandas dataframe from some data.
df = pd.DataFrame({'Numbers':    [1010, 2020, 3030, 2020, 1515, 3030, 4545],
                   'Percentage': [.1,   .2,   .33,  .25,  .5,   .75,  .45 ],
})

# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter("pandas_column_formats.xlsx", engine='xlsxwriter')

# Convert the dataframe to an XlsxWriter Excel object.
df.to_excel(writer, sheet_name='Sheet1')

# Get the xlsxwriter workbook and worksheet objects.
workbook  = writer.book
worksheet = writer.sheets['Sheet1']

# Add some cell formats.
format1 = workbook.add_format({'num_format': '#,##0.00'})
format2 = workbook.add_format({'num_format': '0%'})

# Note: It isn't possible to format any cells that already have a format such
# as the index or headers or any cells that contain dates or datetimes.

# Set the column width and format.
worksheet.set_column('B:B', 18, format1)

# Set the format but not the column width.
worksheet.set_column('C:C', None, format2)

# Close the Pandas Excel writer and output the Excel file.
writer.save()