Excel的生成和导出(POI)
示例
Excel文件:
Jar包准备
Servlet代码
import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFFont; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; public class ExcelServlet extends HttpServlet{ private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } /** * 生成和导出 */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String[] title = {"姓名","性别","年龄"}; List<String[]> content = new ArrayList<String[]>(); String[] four = {"四叶","女","17"}; String[] five = {"五月","女","17"}; content.add(four); content.add(five); HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet = wb.createSheet("五等分的花嫁");//Sheet名 HSSFRow row = sheet.createRow(0);//行 HSSFCellStyle style = wb.createCellStyle();//样式 HSSFFont font = wb.createFont();//字体 style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//居中 font.setFontName("宋体"); font.setFontHeightInPoints((short) 11);//字体大小 style.setFont(font); //单元格 HSSFCell cell = null; //第一行 for(int i=0;i<title.length;i++){ cell = row.createCell(i); cell.setCellValue(title[i]); cell.setCellStyle(style); } //内容 int i=1; for(String[] str:content){ row = sheet.createRow(i++); for(int j=0;i<str.length;j++){ cell = row.createCell(j); cell.setCellValue(str[j]); cell.setCellStyle(style); } } response.setContentType("application/octet-stream;charset=ISO8859-1"); response.setHeader("Content-Disposition","attachment;filename="+ new String("demo.xls".getBytes(),"ISO8859-1")); response.addHeader("Pargam", "no-cache"); response.addHeader("Cache-Control", "no-cache"); wb.write(response.getOutputStream()); response.getOutputStream().flush(); response.getOutputStream().close(); } }