POI表格导出
参考文章
https://www.cnblogs.com/abc8023/p/5843230.html
https://blog.csdn.net/huluedeai/article/details/50544242
文章要点
1.POI导出表格的步骤
2.POI导出表格时,设置单元格的格式
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormat;
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;
public class test {
public static final String CONTENT_TYPE_EXCEL = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
public void downLoad(HttpServletResponse response) {
response.setContentType(CONTENT_TYPE_EXCEL);
response.setHeader("Content-Disposition", "attachment;filename=\"DonwloadTemplet.XLSX\"");
OutputStream out = null;
//数据源
List<String> names = new ArrayList<String>();
try {
Workbook workBook = new XSSFWorkbook();
Sheet sheet = workBook.createSheet();
// set coloum name
Row coloumRow = sheet.createRow(0);
Cell cell01 = coloumRow.createCell(0);
cell01.setCellValue("name");
Cell cell02 = coloumRow.createCell(1);
cell02.setCellValue("age");
Cell cell03 = coloumRow.createCell(2);
cell03.setCellValue("gender");
Cell cell04 = coloumRow.createCell(3);
cell04.setCellValue("birthday");
Cell cell05 = coloumRow.createCell(4);
cell05.setCellValue("money");
//设置单元格的格式
//小数点后保留两位
CellStyle styleNumber = workBook.createCellStyle();
DataFormat format = workBook.createDataFormat();
styleNumber.setDataFormat(format.getFormat("#,#0.00"));
//日期格式
CellStyle styleDate = workBook.createCellStyle();
styleDate.setDataFormat(format.getFormat("MM/dd/yyyy HH:mm:ss"));
// set excel
for (int i = 0; i < names.size(); i++) {
Row row = sheet.createRow(i + 1);
// 在一行内循环
//1. name
Cell cell0 = row.createCell(0);
cell0.setCellValue("");
//2. age
Cell cell1 = row.createCell(1);
cell1.setCellValue(22);
//3. gender
Cell cell2 = row.createCell(2);
cell2.setCellValue("male");
//4. birthday
Cell cell3 = row.createCell(3);
cell3.setCellStyle(styleDate);
cell3.setCellValue(new Date());
//5. money
Cell cell4 = row.createCell(4);
cell4.setCellStyle(styleNumber);
cell4.setCellValue(new BigDecimal(100000000).doubleValue());
}
out = response.getOutputStream();
workBook.write(out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.flush();
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}