如何把数据分割到不同的 Excel 文件中?
如下图所示,希望能在打印的时候,使头两行为重复行,数据部分,按公司名分开,显示不同公司的数据。
回答:
这个需要借助 Excel 本身的分页符和重复行功能。
配置分页符:https://www.grapecity.com.cn/developer/grapecitydocuments/exc...
配置顶部重复行:https://www.grapecity.com.cn/developer/grapecitydocuments/exc...
代码如下:
public void SplitData() { Workbook wb = new Workbook();
IWorksheet sheet = wb.getWorksheets().get(0);
Object data = new Object[][]{
{"A", "A1", "A2"},
{"A", "A1", "A2"},
{"A", "A1", "A2"},
{"A", "A1", "A2"},
{"B", "B1", "B2"},
{"B", "B1", "B2"},
{"B", "B1", "B2"},
{"B", "B1", "B2"},
{"B", "B1", "B2"},
{"C", "C1", "C2"},
{"C", "C1", "C2"},
{"C", "C1", "C2"},
{"C", "C1", "C2"},
};
sheet.getRange("A1:C1").merge();
sheet.getRange("A1:C1").setValue("公司信息");
sheet.getRange("A2").setValue("公司名");
sheet.getRange("B2").setValue("数据1");
sheet.getRange("C2").setValue("数据2");
sheet.getRange("A3:C15").setValue(data);
sheet.getHPageBreaks().add(sheet.getRange("A7"));
sheet.getHPageBreaks().add(sheet.getRange("A12"));
sheet.getPageSetup().setPrintTitleRows("$1:$2");
wb.save("output/SplitData.pdf");
}
结果:
回答:
把数据处理成Map<CompanyName,List<CompanyData>> data
结构,把生成excel的代码封装成一个函数,循环这个Map, 传入CompanyName 和 List<CompanyData> 就可以啦
回答:
import csvdef split_csv_by_company(csv_file):
with open(csv_file, newline='', encoding='utf-8') as file:
reader = csv.reader(file)
table_name = next(reader) # 读取第一行作为表格名称
headers = next(reader) # 读取第二行作为标题行
current_company = None
company_data = {}
for row in reader:
company_name = row[0]
if company_name not in company_data:
company_data[company_name] = []
company_data[company_name].append(row)
for company_name, data in company_data.items():
save_data_to_file(company_name, table_name, headers, data)
def save_data_to_file(company_name, table_name, headers, data):
filename = f"{table_name[0]}_{company_name}.csv"
with open(filename, 'w', newline='', encoding='utf-8') as file:
writer = csv.writer(file)
writer.writerow(table_name)
writer.writerow(headers)
writer.writerows(data)
# 调用示例
split_csv_by_company('data.csv')
如果你会python,那非常简单,如果不会,那也不用看我这个了!
以上是 如何把数据分割到不同的 Excel 文件中? 的全部内容, 来源链接: utcz.com/p/945373.html