赞
踩
查了几天的资料和文章,发现找到的不是合并不了单元格或者就是格式有误.
最后有幸看到一篇文章,并借助之前实现的逻辑最终完成。
https://blog.csdn.net/jishulaozhuanjia/article/details/104951304
废话不多说,上代码
安装HTMLTable包
pip install html-table
import xlrd from HTMLTable import HTMLTable def get_merged_cells(sheet): """ 获取所有的合并单元格,格式如下: [(4, 5, 2, 4), (5, 6, 2, 4), (1, 4, 3, 4)] (4, 5, 2, 4) 的含义为:行 从下标4开始,到下标5(不包含) 列 从下标2开始,到下标4(不包含),为合并单元格 :param sheet: :return: """ return sheet.merged_cells def get_merged_cells_value(sheet, row_index, col_index): """ 先判断给定的单元格,是否属于合并单元格; 如果是合并单元格,就返回合并单元格的内容 :return: """ merged = get_merged_cells(sheet) for (rlow, rhigh, clow, chigh) in merged: if (row_index >= rlow and row_index < rhigh): if (col_index >= clow and col_index < chigh): cell_value = sheet.cell_value(rlow, clow) # print('该单元格[%d,%d]属于合并单元格,值为[%s]' % (row_index, col_index, cell_value)) return cell_value return None def excel_data(xlsxPath,htmlCos): data = xlrd.open_workbook(xlsxPath) # xlsx数据 table_sheet = data.sheet_by_index(0) # sheet索引为table_num tableRows = table_sheet.nrows # excel的行数 tableCols = table_sheet.ncols # excel的列数 merge = table_sheet.merged_cells # 合并的单元格 table_list = [] for r in range(tableRows): # 一行数据的实体类 entity_list = [] for c in range(tableCols): cell_value = table_sheet.row_values(r)[c] # print('第%d行第%d列的值:[%s]' % (r, c, sheet2.row_values(r)[c])) if (cell_value is None or cell_value == ''): cell_value = (get_merged_cells_value(table_sheet, r, c)) # 动态设置各属性值 entity_list.append(cell_value) table_list.append(entity_list) # 创建表格对象 table = HTMLTable() # 表头添加数据 # table.append_header_rows(( # tuple(table_list[0]), # )) # 表格内容添加数据 i=0 # 用于过滤表头的数据 for data in table_list: # if i!=0: table.append_data_rows(( tuple(data), )) i+=1 # 表格样式,即</table><table>标签样式 table.set_style({ 'border-collapse': 'collapse' }) # 表格行样式 table.set_row_style({ 'border-top': '1px solid #333', 'border-left': '1px solid #333', }) # 表格单元格样式 table.set_cell_style({ 'border-bottom': '1px solid #333', 'border-right': '1px solid #333', 'text-align': 'center' }) # 合并的列行 for m in merge: table[m[0]][m[2]].attr.colspan =m[3] - m[2] # 横向合并 table[m[0]][m[2]].attr.rowspan = m[1] - m[0] # 纵向合并 # 生成html html = table.to_html() with open(htmlCos, "w",encoding="utf-8") as f: f.write("<html> " "<body>") f.write(html) f.write("</body>" "</html> ") if __name__ == '__main__': excel_data('jh2.xlsx','33.html')
第一次写,有不好多担待,欢迎指出问题。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。