导入的包是jxl的包
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
public class WriteExcel {
//btlist标题栏和相关字段
//nrlist内容
//wjm文件名
public static void WriteExcel(List<Fields> btlist,List<Map<String, Object>> nrlist,String wjm){
try {
int length=btlist.size();//获取字段数目
FileOutputStream fos=new FileOutputStream("C:\\zc.xls");//文件的输出位置
WritableWorkbook workbook=Workbook.createWorkbook(fos);
WritableSheet sheet=workbook.createSheet("First sheet", 0);
//设置一下标题样式
WritableFont bold=new WritableFont(WritableFont.ARIAL,10,WritableFont.BOLD);
WritableCellFormat btformat=new WritableCellFormat(bold);
//保存标题
for (int i = 0; i < length; i++) {
Label label=new Label(i, 0, btlist.get(i).getFIELD_SHOW_NAME(),btformat);
sheet.addCell(label);
}
//保存内容
for (int i = 0; i <nrlist.size(); i++) {
for (int j = 0; j <length; j++) {
Label label=new Label(j, i+1, String.valueOf(nrlist.get(i).get(btlist.get(j).getFIELD_NAME())));
sheet.addCell(label);
}
}
workbook.write();
workbook.close();
fos.close();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("失败",e);
}
}
public static void main(String[] args) {
}
}
如果用poi的话,方法如下(这个是直接在编辑器里写的,可能有小错误,但大概方法就是这样)
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
/**
* 生成excel文件
*
*/
@Service
public class TaskStepsFileService implements ITaskStepsFileService{
private static final String FILE_NAME= "FileName";
public void CreateExcel(List<List<String>> datalist) throws IOException {
Workbook wb = new XSSFWorkbook();//如果想生成03版的,换一个Workbook就行了
createDataSheet(wb, FILE_NAME, datalist);
FileOutputStream fileOut = new FileOutputStream("C:/zc.xlsx");
wb.write(fileOut);
fileOut.close();
wb.close();
}
private Sheet createDataSheet(Workbook wb, String sheetName,List<List<String>> listDatas) {
Sheet sheet = wb.createSheet(sheetName);
int rowIndex = 0;
//这里循环放入内容
for (int j = 0; j <listDatas.size(); j++) {
Row row=sheet.createRow(rowIndex++);
for (int i = 0; i <listData.get(j).size(); i++) {
Cell cell=row.createCell(i);
cell.setCellValue(listData.get(j).get(i));
}
return sheet;
}
}