我们知道要创建一张excel你得知道excel由什么组成,比如说sheet也就是一个工作表格,例如一行,一个单元格,单元格格式,单元格内容格式…这些都对应着poi里面的一个类。一个excel表格:

HSSFWorkbook wb = new HSSFWorkbook();

一个工作表格(sheet):

HSSFSheet sheet = wb.createSheet("测试表格");

一行(row):

HSSFRow row1 = sheet.createRow(0);

一个单元格(cell):

HSSFCell cell2 = row2.createCell((short)0)

单元格格式(cellstyle):

HSSFCellStyle style4 = wb.createCellStyle()

单元格内容格式()HSSFDataFormat format= wb.createDataFormat();

1:首先创建一个po对象

package entity;

public class Student {
    private int no;
    private String name;
    private int age;
    private String grage;
    public Student(int no, String name, int age, String grage) {
        super();
        this.no = no;
        this.name = name;
        this.age = age;
        this.grage = grage;
    }
    public int getNo() {
        return no;
    }
    public void setNo(int no) {
        this.no = no;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getGrage() {
        return grage;
    }
    public void setGrage(String grage) {
        this.grage = grage;
    }
    
}

2实现导出的功能:

 package demo;
 
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.sql.SQLException;
 import java.util.ArrayList;
 import java.util.Date;
 import java.util.List;
 
 import org.apache.poi.hssf.usermodel.HSSFCell;
 import org.apache.poi.hssf.usermodel.HSSFCellStyle;
 import org.apache.poi.hssf.usermodel.HSSFDataFormat;
 import org.apache.poi.hssf.usermodel.HSSFRow;
 import org.apache.poi.hssf.usermodel.HSSFSheet;
 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
 import org.apache.poi.hssf.util.Region;
 import org.apache.poi.ss.usermodel.Font;
 
 import entity.Student;
 
 public class Export_demo {
     public static void main(String[] args) {
         export();
     }
     
     public static void export(){
         List<Student> studens=new ArrayList<Student>();
         for (int i = 1; i <=20; i++) {
             Student s=new Student(i, "a"+i, 20+i-20, "三年级");
             studens.add(s);
         }
         
         HSSFWorkbook wb = new HSSFWorkbook();//创建一个excel文件
         HSSFSheet sheet=wb.createSheet("学生信息");//创建一个工作薄
         sheet.setColumnWidth((short)3, 20* 256);    //---》设置单元格宽度,因为一个单元格宽度定了那么下面多有的单元格高度都确定了所以这个方法是sheet的  
         sheet.setColumnWidth((short)4, 20* 256);    //--->第一个参数是指哪个单元格,第二个参数是单元格的宽度  
         sheet.setDefaultRowHeight((short)300);    // ---->有得时候你想设置统一单元格的高度,就用这个方法
         HSSFDataFormat format= wb.createDataFormat();   //--->单元格内容格式  
         HSSFRow row1 = sheet.createRow(0);   //--->创建一行  
           // 四个参数分别是:起始行,起始列,结束行,结束列 (单个单元格) 
         sheet.addMergedRegion(new Region(0, (short) 0, 0, (short)5));//可以有合并的作用 
         HSSFCell cell1 = row1.createCell((short)0);   //--->创建一个单元格  
         cell1.setCellValue("学生信息总览");
         
        
         sheet.addMergedRegion(new Region(1, (short) 0, 1, (short)0));
         HSSFRow row2= sheet.createRow(1);   ////创建第二列 标题
         HSSFCell fen = row2.createCell((short)0);   //--->创建一个单元格  
         fen.setCellValue("编号/属性 ");
         HSSFCell no = row2.createCell((short)1);   //--->创建一个单元格  
         no.setCellValue("姓名 ");
         HSSFCell age = row2.createCell((short)2);   //--->创建一个单元格  
         age.setCellValue("年龄 ");
         HSSFCell grage = row2.createCell((short)3);   //--->创建一个单元格  
         grage.setCellValue("年级 ");
         
         for (int i = 0; i <studens .size(); i++) {
              sheet.addMergedRegion(new Region(1+i+1, (short) 0, 1+i+1, (short)0));
             HSSFRow rows= sheet.createRow(1+i+1);   ////创建第二列 标题
             HSSFCell fens = rows.createCell((short)0);   //--->创建一个单元格  
             fens.setCellValue(studens.get(i).getNo());
             HSSFCell nos = rows.createCell((short)1);   //--->创建一个单元格  
             nos.setCellValue(studens.get(i).getName());
             HSSFCell ages = rows.createCell((short)2);   //--->创建一个单元格  
             ages.setCellValue(studens.get(i).getAge());
             HSSFCell grages = rows.createCell((short)3);   //--->创建一个单元格  
             grages.setCellValue(studens.get(i).getGrage());
         }
         FileOutputStream fileOut = null;  
         try{              
             fileOut = new FileOutputStream("d:\\studens.xls");  
             wb.write(fileOut);  
             //fileOut.close();  
             System.out.print("OK");  
         }catch(Exception e){  
             e.printStackTrace();  
         }  
         finally{  
             if(fileOut != null){  
                 try {  
                     fileOut.close();  
                 } catch (IOException e) {  
                     // TODO Auto-generated catch block  
                     e.printStackTrace();  
                 }  
             }  
         }  
     }
 }

效果图:

图片描述

3实现导入的功能:

 package demo;
 
 import java.io.FileInputStream;
 import java.io.FileNotFoundException;
 import java.io.InputStream;
 import java.text.SimpleDateFormat;
 import java.util.ArrayList;
 import java.util.Date;
 import java.util.List;
 
 import org.apache.poi.hssf.usermodel.HSSFCell;
 import org.apache.poi.hssf.usermodel.HSSFDateUtil;
 import org.apache.poi.hssf.usermodel.HSSFRow;
 import org.apache.poi.hssf.usermodel.HSSFSheet;
 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
 import org.apache.poi.poifs.filesystem.POIFSFileSystem;
 
 import entity.Student;
 
 public class Import_demo {
     private static POIFSFileSystem fs;//poi文件流
     private static HSSFWorkbook wb;//获得execl
     private static HSSFRow row;//获得行
     private static HSSFSheet sheet;//获得工作簿
     
     public static void main(String[] args) throws FileNotFoundException {
         InputStream in= new FileInputStream("d:\\studens.xls");
         imports(in);
     }
     
     public static void imports(InputStream in ){
         String str = "";
         try {
              fs = new POIFSFileSystem(in);
              wb = new HSSFWorkbook(fs);
              sheet=wb.getSheetAt(0);
              //int rowfirst=sheet.getFirstRowNum();
              int rowend=sheet.getLastRowNum();
              for (int i = 2; i <=rowend; i++) {
                 row=sheet.getRow(i);
                 //System.out.println(row.get);
                 int colNum = row.getPhysicalNumberOfCells();//一行总列数
                  int j = 0;
                     while (j < colNum) {
                         str += getCellFormatValue(row.getCell((short) j)).trim() + "-";
                         j++;
                     }
                     System.out.println(str);
                     str="";
             }
         } catch (Exception e) {
             // TODO: handle exception
         }
     }
     
     private static String getCellFormatValue(HSSFCell cell) {
         String cellvalue = "";
         if (cell != null) {
             // 判断当前Cell的Type
             switch (cell.getCellType()) {
                 // 如果当前Cell的Type为NUMERIC
                 case HSSFCell.CELL_TYPE_NUMERIC:
                 case HSSFCell.CELL_TYPE_FORMULA: {
                     // 判断当前的cell是否为Date
                     if (HSSFDateUtil.isCellDateFormatted(cell)) {
                         Date date = cell.getDateCellValue();
                         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                         cellvalue = sdf.format(date);
                     }
                     // 如果是纯数字
                     else {
                         // 取得当前Cell的数值
                         cellvalue = String.valueOf(cell.getNumericCellValue());
                     }
                     break;
                 }
                 // 如果当前Cell的Type为STRIN
                 case HSSFCell.CELL_TYPE_STRING:
                     // 取得当前的Cell字符串
                     cellvalue = cell.getRichStringCellValue().getString();
                     break;
                 // 默认的Cell值
                 default:
                     cellvalue = " ";
             }
         } else {
             cellvalue = "";
         }
         return cellvalue;
     }
     
 }

效果:

图片描述

代码和jar宝下载路径
https://download.csdn.net/download/cengjianggh/10418815

---------------------------------------------------------------------------------------------------------------------更新分割线-------------------------------------------------------------------------------------------

2018年7月31日 14:54:00

实现导出poi数据到excel 在浏览器上弹出下载标签

  接受数据查询的参数,然后查询数据库得到list集合的po对象转换为excel然后输出给浏览器

@RequiresPermissions("/actLog/postActLogSel")
    @RequestMapping(value = "/actLog/excel")
    public @ResponseBody  void getexcel(DataGridModel dgm,HttpServletResponse response,HttpServletRequest request) throws Exception {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/x-download");
        String fileName = "埋点登录.xlsx";
        fileName = URLEncoder.encode(fileName, "UTF-8");
        response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
        XSSFWorkbook wb=actLog.getExcel(dgm);
        try {
            OutputStream out = response.getOutputStream();
            wb.write(out);
            out.close();
            wb.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
    }
        }
 if("post".equals(type)){
         List<BsActLog> log=actLog.getActPostcounts(map);
         wb = new XSSFWorkbook();
         XSSFSheet sheet = wb.createSheet("帖子埋点");
         sheet.setColumnWidth(0, 20 * 256);sheet.setColumnWidth(4, 20 * 256);sheet.setColumnWidth(8, 20 * 256);
         sheet.setColumnWidth(1, 20 * 256);sheet.setColumnWidth(5, 20 * 256);sheet.setColumnWidth(9, 20 * 256);
         sheet.setColumnWidth(2, 20 * 256);sheet.setColumnWidth(6, 20 * 256);sheet.setColumnWidth(10, 20 * 256);
         sheet.setColumnWidth(3, 20 * 256);sheet.setColumnWidth(7, 20 * 256);
         XSSFRow row = sheet.createRow(0);
         XSSFCell cell = row.createCell(0);
         cell=getStyle(wb, cell);//设置样式,可以不要
         cell.setCellValue("日期 ");
         XSSFCell cell2 = row.createCell(1);
         cell2.setCellValue("标题 ");
         cell2=getStyle(wb, cell2);
         XSSFCell cell3 = row.createCell(2);
         cell3.setCellValue("用户名 ");
         cell3=getStyle(wb, cell3);
         XSSFCell cell5 = row.createCell(3);
         cell5.setCellValue("PV ");
         cell5=getStyle(wb, cell5);
         XSSFCell cell6 = row.createCell(4);
         cell6.setCellValue("UV ");
         cell6=getStyle(wb, cell6);
         XSSFCell cell7 = row.createCell(5);
         cell7.setCellValue("回复人数 ");
         cell7=getStyle(wb, cell7);
         XSSFCell cell8 = row.createCell(6);
         cell8.setCellValue("回复次数 ");
         cell8=getStyle(wb, cell8);
         XSSFCell cell9 = row.createCell(7);
         cell9.setCellValue("点赞数 ");
         cell9=getStyle(wb, cell9);
         XSSFCell cell10 = row.createCell(8);
         cell10.setCellValue("收藏数 ");
         cell10=getStyle(wb, cell10);
         XSSFCell cell11 = row.createCell(9);
         cell11.setCellValue("是否首页置顶 ");
         cell11=getStyle(wb, cell11);
         XSSFCell cell12 = row.createCell(10);
         cell12.setCellValue("是否置顶 ");
         cell12=getStyle(wb, cell12);
         XSSFCell cell13 = row.createCell(11);
         cell13.setCellValue("是否精华 ");
         cell13=getStyle(wb, cell13);
         int i=1;
         for (BsActLog lo : log) {
             XSSFRow rows = sheet.createRow(i);
             XSSFCell cells = rows.createCell(0);
             cells.setCellValue(lo.getDay());
             cells=getStyle(wb, cells);
             XSSFCell cells2 = rows.createCell(1);
             cells2.setCellValue(lo.getTitle());
             cells2=getStyle(wb, cells2);
             XSSFCell cells3 = rows.createCell(2);
             String name=filterEmoji(lo.getUsername());//对emoji表情过滤,可以不要
             cells3.setCellValue(name);
             cells3=getStyle(wb, cells3);
             XSSFCell cells4 = rows.createCell(3);
             cells4.setCellValue(lo.getPv());
             cells4=getStyle(wb, cells4);
             XSSFCell cells5 = rows.createCell(4);
             cells5.setCellValue(lo.getUv());
             cells5=getStyle(wb, cells5);
             XSSFCell cells6 = rows.createCell(5);
             cells6.setCellValue(lo.getReplyperson());
             cells6=getStyle(wb, cells6);
             XSSFCell cells7 = rows.createCell(6);
             cells7.setCellValue(lo.getReplycount());
             cells7=getStyle(wb, cells7);
             XSSFCell cells8 = rows.createCell(7);
             cells8.setCellValue(lo.getLikecount());
             cells8=getStyle(wb, cells8);
             XSSFCell cells9 = rows.createCell(8);
             cells9.setCellValue(lo.getCollectcount());
             cells9=getStyle(wb, cells9);
             XSSFCell cells10 = rows.createCell(9);
             cells10.setCellValue(lo.getIsmainpagetop());
             cells10=getStyle(wb, cells10);
             XSSFCell cells11 = rows.createCell(10);
             cells11.setCellValue(lo.getIstop());
             cells11=getStyle(wb, cells11);
             XSSFCell cells12 = rows.createCell(11);
             cells12.setCellValue(lo.getIsdigestpost());
             cells12=getStyle(wb, cells12);
             i+=1;
         }
     }

如果浏览器弹不出下载框,则把前台的请求改为get请求window.open('地址?'参数);

过滤emoji表情的方法

 public static String filterEmoji(String source)//过滤emoji表情
 {
    if(source==null ||"".equals(source))
    {
        return "";
    }
     if (!containsEmoji(source))
     {
         return source; //如果不包含,直接返回
     }
     //到这里铁定包含
     StringBuilder buf = null;
     int len = source.length();
     for (int i = 0; i < len; i++)
     {
         char codePoint = source.charAt(i);
         if (!isEmojiCharacter(codePoint))
         {
             if (buf == null)
             {
                 buf = new StringBuilder();
             }
             buf.append(codePoint);
         } else { } }
     if (buf == null)
     {
         return source; //如果没有找到 emoji表情,则返回源字符串
     }
     else
     {
         if (buf.length() == len)
         {
             //这里的意义在于尽可能少的toString,因为会重新生成字符串
             buf = null;
             return source;
         }
         else
         {
             return buf.toString();
         }
     }
 }
 public static boolean containsEmoji(String source)
 {
     if (source==null ||"".equals(source))
     {
         return false;
     }
     int len = source.length();
     for (int i = 0; i < len; i++)
     {
         char codePoint = source.charAt(i);
         if (isEmojiCharacter(codePoint))
         {
             //do nothing,判断到了这里表明,确认有表情字符
             return true;
         }
     }
     return false;
 }
 public static boolean isEmojiCharacter(char codePoint)
 {
     return (codePoint >= 0x2600 &amp;&amp; codePoint <= 0x27BF) // 杂项符号与符号字体
            || codePoint == 0x303D
            || codePoint == 0x2049
            || codePoint == 0x203C
            || (codePoint >= 0x2000 &amp;&amp; codePoint <= 0x200F) //
            || (codePoint >= 0x2028 &amp;&amp; codePoint <= 0x202F) //
            || codePoint == 0x205F //
            || (codePoint >= 0x2065 &amp;&amp; codePoint <= 0x206F) //
                                                            /* 标点符号占用区域 */
            || (codePoint >= 0x2100 &amp;&amp; codePoint <= 0x214F) // 字母符号
            || (codePoint >= 0x2300 &amp;&amp; codePoint <= 0x23FF) // 各种技术符号
            || (codePoint >= 0x2B00 &amp;&amp; codePoint <= 0x2BFF) // 箭头A
            || (codePoint >= 0x2900 &amp;&amp; codePoint <= 0x297F) // 箭头B
            || (codePoint >= 0x3200 &amp;&amp; codePoint <= 0x32FF) // 中文符号
            || (codePoint >= 0xD800 &amp;&amp; codePoint <= 0xDFFF) // 高低位替代符保留区域
            || (codePoint >= 0xE000 &amp;&amp; codePoint <= 0xF8FF) // 私有保留区域
            || (codePoint >= 0xFE00 &amp;&amp; codePoint <= 0xFE0F) // 变异选择器
                                                            //   || (codePoint >= U + 2600 &amp;&amp; codePoint <= 0xFE0F)
            || codePoint >= 0x10000; // Plane在第二平面以上的,char都不可以存,全部都转
 }