实用: 将程序的内容写出到excel中
pom
<!-- 读取excel文件 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
实体
public class CowRecord {
private String code;
private String year;
}
写逻辑
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class WriteExcel {
public static void main(String[] args) {
List<CowRecord> list = new ArrayList<CowRecord>();
for (int i = 0; i < 10; i++) {
CowRecord cowRecord = new CowRecord();
cowRecord.setCode("code" + i);
cowRecord.setYear("year" + i);
list.add(cowRecord);
}
write(list);
}
public static void write(List<CowRecord> sortList) {
// 创建工作薄
HSSFWorkbook workbook = new HSSFWorkbook();
// 创建工作表
HSSFSheet sheet = workbook.createSheet("sheet1");
int rowNum = sortList.size() + 1;
for (int row = 0; row < rowNum; row++) {
HSSFRow rows = sheet.createRow(row);
//表头
if(row ==0){
rows.createCell(0).setCellValue("证券代码");
rows.createCell(1).setCellValue("会计期间'");
}else{
CowRecord cowData = sortList.get(row - 1);
for (int col = 0; col < 30; col++) {
// 向工作表中添加数据
switch (col){
case 0:
rows.createCell(col).setCellValue(cowData.getCode());
break;
case 1:
rows.createCell(col).setCellValue(cowData.getYear());
break;
}
}
}
}
try {
File xlsFile = new File("/Users/t/Desktop/data/w.xls");
FileOutputStream xlsStream = new FileOutputStream(xlsFile);
workbook.write(xlsStream);
}catch (Exception e){
e.printStackTrace();
}
}
}