记录一次帮生物同学转excel样本数据
1 前言
程序写得有点烂,大家看着乐就行。
同学的需求:将一个只有两种数据的excel表转成一个二维表,即某样地中有的植物对应二维表中就为1,没有就填入0。
如下:
源数据文件
要返回的数据文件
2 第一次实现
刚开始的想法很简单,就是把存放在excel的源数据读取并存到数据库,先查询相应的种类名和样地(查询中用到distinct),建立第一行和第一列的数据。
然后类似一个二维数组的操作一样,遍历将第一列的每一个样地加上第一行的种类名去查询有没有对应的plant数据,有就将对应的excel格子设为1,没有就设为0。
2.1 代码
/**
* xlsx类型
* @return
*/
public XSSFWorkbook writeXLSX() {
//获取种类名
List<String> plant = plantService.getPlant();
//获取样地
List<String> sample = plantService.getSample();
System.out.println(plant);
System.out.println(sample);
//创建excel
XSSFWorkbook sheets = new XSSFWorkbook();
XSSFSheet sheet = sheets.createSheet();
XSSFRow firstRow = sheet.createRow(0);
int index = 0;
//设置表头
for (int i = 1;i < plant.size()+1;i++){
XSSFCell cell = firstRow.createCell(i);
String name = plant.get(index++);
cell.setCellValue(name);
}
index = 0;
for (int i = 1;i < sample.size()+1;i++){
XSSFRow row = sheet.createRow(i);
String sple = sample.get(index++);
row.createCell(0).setCellValue(sple);
}
index = 0;
for (int i = 1;i < sample.size()+1;i++){
String sple = sample.get(index++);
for (int j = 1; j < plant.size()+1; j++) {
XSSFRow firstrow = sheet.getRow(0);
XSSFCell cell = firstrow.getCell(j);
String name = cell.getStringCellValue();