在现有Excel工作簿中更改列内容格式
我想要改变Excel工作簿中内容的格式。
环境:Windows 7;Python 2.76
我想把A、B和C列改成我想要的格式。现在我有的是:
from openpyxl import Workbook
from openpyxl import load_workbook
wb = load_workbook('c:\\oldfile.xls')
ws = wb.active
d = ws.cell(column = 0) # or 1, 2, 3
d.style = Style(font=Font(bold=False),
borders=Borders(left=Border(border_style='none'),
right=Border(border_style='none'),
top=Border(border_style='none'),
bottom=Border(border_style='none')),
color=Color(Color.RED))
wb.save('c:\\oldfile.xls')
显然,我指示列的方式是错的。那么我有几个问题:
- 如何改变整列内容的格式?
- 因为“openpyxl”只能处理.xlsx和.xlsm格式的文件,如果原文件是.xls格式的,我该如何改变格式(而不把文件转换成.xlsx)?
谢谢。
这是使用'easyxf',不过它会把所有内容都格式化。
import xlwt
from xlrd import open_workbook
from xlutils.copy import copy
from xlwt import easyxf
old_file = open_workbook('c:\\oldfile.xls',formatting_info=True)
old_sheet = old_file.sheet_by_index(0)
new_file = copy(old_file)
new_sheet = new_file.get_sheet(0)
style = easyxf('font: bold false;'
'borders: left no_line, right no_line, top no_line, bottom no_line;'
'font: color red')
row_data = []
for row_index in range(old_sheet.nrows):
rows = old_sheet.row_values(row_index)
row_data.append(rows)
for row_index, row in enumerate(row_data):
for col_index, cell_value in enumerate(row):
new_sheet.write(row_index, col_index, cell_value, style)
new_file.save('c:\\newfile.xls')
#and to use os.rename and remove to make it looked like only worked on 1 file
2 个回答
1
我不知道有什么Python工具可以把.xls
文件转换成.xlsx
文件。你可以简单地把两个库结合起来使用:用xlrd
来读取文件,用openpyxl
或者xlsxwriter
来写入文件。openpyxl
确实支持用ColumnDimension
和RowDimension
对象来格式化整列和整行。
0
其实,"well, found"只是说明这些列需要在写作中进行格式化,其实是可以做到的。
把它们放在一起可能会有帮助:
import xlwt
from xlrd import open_workbook
from xlutils.copy import copy
from xlwt import easyxf
old_file = open_workbook('c:\\oldfile.xls',formatting_info=True)
old_sheet = old_file.sheet_by_index(0)
new_file = copy(old_file)
new_sheet = new_file.get_sheet(0)
style = easyxf('font: bold true;'
'borders: left no_line, right no_line, top no_line, bottom no_line;'
'font: color red')
row_data = []
for row_index in range(old_sheet.nrows):
rows = old_sheet.row_values(row_index)
row_data.append(rows)
for row_index, row in enumerate(row_data):
for col_index, cell_value in enumerate(row):
# indicate the columns want to be formatted
if col_index == 0 or col_index == 1:
new_sheet.write(row_index, col_index, cell_value, style)
else:
new_sheet.write(row_index, col_index, cell_value)
new_file.save('c:\\newfile.xls')