zoukankan      html  css  js  c++  java
  • java利用poi生成/读取excel表格、生成word

    1.引入jar包依赖

       

    <dependency>
                <groupId>org.apache.poi</groupId>
                <artifactId>poi</artifactId>
                <version>3.9</version>
            </dependency>
    
            <dependency>
                <groupId>org.apache.poi</groupId>
                <artifactId>poi-ooxml</artifactId>
                <version>3.8</version>
            </dependency>
    View Code

    2.编写代码测试

      1 package testweb;
      2 
      3 import java.io.File;
      4 import java.io.FileNotFoundException;
      5 import java.io.FileOutputStream;
      6 import java.io.IOException;
      7 import java.io.OutputStream;
      8 import java.util.LinkedList;
      9 import java.util.List;
     10 
     11 import org.apache.poi.hssf.usermodel.HSSFCell;
     12 import org.apache.poi.hssf.usermodel.HSSFCellStyle;
     13 import org.apache.poi.hssf.usermodel.HSSFFont;
     14 import org.apache.poi.hssf.usermodel.HSSFRichTextString;
     15 import org.apache.poi.hssf.usermodel.HSSFRow;
     16 import org.apache.poi.hssf.usermodel.HSSFSheet;
     17 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
     18 import org.apache.poi.hssf.util.HSSFColor;
     19 
     20 
     21 public class TestExcel {
     22 
     23     public static void main(String[] args) {
     24         List<Object> l=new LinkedList<>();
     25         l.add("zs");
     26         l.add("ls");
     27         l.add("we");
     28         l.add("mz");
     29         String[] headers=new String[]{"tou1","tou2","tou3","tou4"};
     30         try {
     31             OutputStream o= new FileOutputStream(new File("C:/Users/yanan/Desktop/yanantest.xls"));
     32             exportDataExcel("nihao",headers,l,o);
     33         } catch (FileNotFoundException e) {
     34             e.printStackTrace();
     35         }
     36     }
     37     
     38     protected static void exportDataExcel(String title,String[] headers,List<Object> mapList,OutputStream out){  
     39         //声明一个工作簿  
     40         HSSFWorkbook workbook = new HSSFWorkbook();  
     41         //生成一个表格  
     42         HSSFSheet sheet = workbook.createSheet(title);  
     43         //设置表格默认列宽度字符  
     44         sheet.setDefaultColumnWidth(20);  
     45         //生成一个样式,用来设置标题样式  
     46         HSSFCellStyle style = workbook.createCellStyle();  
     47         //设置这些样式  
     48         style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);  
     49         style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);  
     50         style.setBorderBottom(HSSFCellStyle.BORDER_THIN);  
     51         style.setBorderLeft(HSSFCellStyle.BORDER_THIN);  
     52         style.setBorderRight(HSSFCellStyle.BORDER_THIN);  
     53         style.setBorderTop(HSSFCellStyle.BORDER_THIN);  
     54         style.setAlignment(HSSFCellStyle.ALIGN_CENTER);  
     55         //生成一个字体  
     56         HSSFFont font = workbook.createFont();  
     57         font.setColor(HSSFColor.VIOLET.index);  
     58         font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);  
     59         //把字体应用到当前的样式  
     60         style.setFont(font);  
     61         // 生成并设置另一个样式,用于设置内容样式  
     62         HSSFCellStyle style2 = workbook.createCellStyle();  
     63         style2.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);  
     64         style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);  
     65         style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);  
     66         style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);  
     67         style2.setBorderRight(HSSFCellStyle.BORDER_THIN);  
     68         style2.setBorderTop(HSSFCellStyle.BORDER_THIN);  
     69         style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);  
     70         style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);  
     71         // 生成另一个字体  
     72         HSSFFont font2 = workbook.createFont();  
     73         font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);  
     74         // 把字体应用到当前的样式  
     75         style2.setFont(font2);  
     76         //产生表格标题行  
     77         HSSFRow row = sheet.createRow(0);  
     78         for (int i = 0; i < headers.length; i++) {
     79             HSSFCell cell = row.createCell(i);
     80             cell.setCellStyle(style);
     81             HSSFRichTextString text = new HSSFRichTextString(headers[i]);
     82             cell.setCellValue(text);
     83         }
     84         for (int i = 0; i < mapList.size(); i++) {
     85             row = sheet.createRow(i + 1);
     86             int j = 0;
     87             HSSFCell cell = row.createCell(j++);
     88             cell.setCellValue("循环获得值1");
     89             cell.setCellStyle(style2);
     90             row.createCell(j++).setCellValue("循环获得值2");
     91             row.createCell(j++).setCellValue("循环获得值3");
     92             row.createCell(j++).setCellValue("循环获得值4");
     93         }
     94         try {
     95             workbook.write(out);
     96         } catch (IOException e) {
     97             e.printStackTrace();
     98         }
     99     } 
    100 }
    View Code
    package testweb;
    
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStream;
    import java.text.DecimalFormat;
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    import org.apache.poi.hssf.usermodel.HSSFDateUtil;
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    import org.apache.poi.poifs.filesystem.POIFSFileSystem;
    import org.apache.poi.ss.usermodel.Cell;
    import org.apache.poi.ss.usermodel.Row;
    import org.apache.poi.ss.usermodel.Sheet;
    
    public class TestExcel {
        public static void main(String[] args) {
            try {
                FileInputStream file = new FileInputStream("C:/Users/yanan/Desktop/yanan.xls");
                List<Map<String, Object>> yanantest = duquexcel(file);
                for (Map<String, Object> item : yanantest) {
                    System.out.println(item.get("id") + "," + item.get("name") + "," + item.get("gendar")+","+item.get("time"));
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    
        public static List<Map<String, Object>> duquexcel(InputStream fis) {
            List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
            HSSFWorkbook wb;
            try {
                wb = new HSSFWorkbook(new POIFSFileSystem(fis));
                Sheet sheet = wb.getSheetAt(0);
                // 日期格式化
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy/M/dd");
                // 数字格式化
                DecimalFormat df = new DecimalFormat("##");
                // 循环xls中的每个表格
                Row firstRow = sheet.getRow(0);
    
                for (int i = sheet.getFirstRowNum() + 1; i <= sheet.getLastRowNum(); i++) {
                    Row row = sheet.getRow(i);
                    Map<String, Object> rowMap = new HashMap<String, Object>();
    
                    for (int k = 0; k < row.getLastCellNum(); k++) {
                        Cell cell = row.getCell(k);
                        if (null == cell) {
                            continue;
                        }
                        switch (cell.getCellType()) {
                        case Cell.CELL_TYPE_NUMERIC:
                            if(HSSFDateUtil.isCellDateFormatted(cell)){
                                rowMap.put(firstRow.getCell(k).getStringCellValue(),sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue())) );
                                break;
                            }
                            double value_d = cell.getNumericCellValue();
                            long value_l = (long) cell.getNumericCellValue();// cell.getCellStyle()获取样式
                            if (value_d == value_l)
                                rowMap.put(firstRow.getCell(k).getStringCellValue(), String.valueOf(value_l));
                            else
                                rowMap.put(firstRow.getCell(k).getStringCellValue(), String.valueOf(value_d));
                            break;
                        case Cell.CELL_TYPE_STRING:
                            rowMap.put(firstRow.getCell(k).getStringCellValue(), cell.getStringCellValue());
                            break;
                        case Cell.CELL_TYPE_BLANK:
                            break;
                        default:
                            rowMap.put(firstRow.getCell(k).getStringCellValue(), cell.toString());
                            break;
                        }
                    }
                    // 是否空行
                    if (rowMap.size() > 0) {
                        resultList.add(rowMap);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return resultList;
        }
    }
    View Code

    20200606之前的写法有些啰嗦,来个简单点的@参考博客@官方文档@参考地址3@参考博客4

    引入依赖

            <!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
            <dependency>
                <groupId>org.apache.poi</groupId>
                <artifactId>poi</artifactId>
                <version>4.1.2</version>
            </dependency>
    View Code

    代码:

            //得到Excel工作簿对象    
            HSSFWorkbook wb=new HSSFWorkbook ();
            //得到Excel工作表对象    
            HSSFSheet sheet =wb.createSheet("sheet名称");  
            //创建行
            HSSFRow row0 =sheet.createRow(0); 
            //创建单元格
            row0.createCell(0).setCellValue("单元格值");
    View Code
    POIFSFileSystem fs=newPOIFSFileSystem(new FileInputStream("d:/test.xls"));   
    //得到Excel工作簿对象    
    HSSFWorkbook wb = new HSSFWorkbook(fs);  
    //得到Excel工作表对象    
    HSSFSheet sheet = wb.getSheetAt(0);   
    //得到Excel工作表的行    
    HSSFRow row = sheet.getRow(i);  
    //得到Excel工作表指定行的单元格    
    HSSFCell cell = row.getCell((short) j);  
    cellStyle = cell.getCellStyle();//得到单元格样式  
    View Code

    导出excel

            //application/octet-stream
            response.setCharacterEncoding("UTF-8");
         response.setContentType("application/vnd.ms-excel");//生成xls的
            response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode("文件名称", "UTF-8")+".xls");  response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
         wb.close();
    View Code
    java.net.URLEncoder.encode("文件名称", "UTF-8")是为了防止文件名中文乱码
    仅靠上述代码是文件有可能乱码,即便进行了如下设置(
    测试发现,这样写也是没起任何作用)
    response.setContentType("application/ms-excel;charset=utf-8");

    经验证,在controller中添加produces属性即可

    @RequestMapping(value = { "/" }, produces =  "application/octet-stream")

    如果需要生成xlsx格式的代码,需要调整一下。增加poi-ooxml依赖

            <!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
            <dependency>
                <groupId>org.apache.poi</groupId>
                <artifactId>poi</artifactId>
                <version>4.1.2</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
            <dependency>
                <groupId>org.apache.poi</groupId>
                <artifactId>poi-ooxml</artifactId>
                <version>4.1.2</version>
            </dependency>
    View Code

    更改相关类

    @RequestMapping(value = { "/exportAnswerExcel2" }, method = {RequestMethod.GET },produces = "application/octet-stream")
    @ResponseBody
    public void exportAnswerExcel2(HttpServletRequest req,HttpServletResponse res) {
    
          //得到Excel工作簿对象 
    
          Workbook wb = new XSSFWorkbook();
    
          //得到Excel工作表对象    
    
            Sheet sheet = wb.createSheet("工作簿名称");  
            //创建行
            Row row0 = sheet.createRow(0); 
            //创建单元格并赋值
            row0.createCell(0).setCellValue("单元格值");   
            res.setCharacterEncoding("UTF-8");
         response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");//生成xlsx的
            res.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode("excel文件名" "UTF-8")+".xlsx");  
            res.addHeader("Pargam", "no-cache");
            res.addHeader("Cache-Control", "no-cache");
            OutputStream os = res.getOutputStream();
           wb.write(os);
           os.flush();
            os.close();
            wb.close(); 
    }        
    View Code

    区别是

    new HSSFWorkbook ();是用来生成xls的,new XSSFWorkbook();是用来生成xlsx的

    20200702:生成word,参考博客:

    https://www.cnblogs.com/duanrantao/p/8682897.html

    https://blog.csdn.net/zhouseawater/article/details/54289495

    https://www.cnblogs.com/yfrs/p/wordpoi.html

    https://blog.csdn.net/yinlei144/article/details/19316569

    https://blog.csdn.net/weixin_43009990/article/details/89704258

    java导出代码:

        public static void main(String[] args) throws IOException {
            XWPFDocument document= new XWPFDocument();
            //添加标题
            XWPFParagraph titleParagraph = document.createParagraph();
            //设置段落居中
            titleParagraph.setAlignment(ParagraphAlignment.CENTER);
        
            // 标题
            XWPFRun titleParagraphRun = titleParagraph.createRun();
            // 然后把你查出的数据插入到document中去就可以了
            titleParagraphRun.setText("AAA");
            // 设置字体颜色
            titleParagraphRun.setColor("000000");
            // 设置字体大小
            titleParagraphRun.setFontSize(15);
            titleParagraphRun.setFontFamily("宋体");
        
            //段落
            XWPFParagraph firstParagraph = document.createParagraph();
            XWPFRun run = firstParagraph.createRun();
            run.setText("BBB");
            run.setColor("000000");
            run.setFontSize(10);
            run.setText("	CCC☑○⊙");
            run.setColor("000000");
            run.setFontSize(12);
            //换行
            XWPFParagraph paragraph1 = document.createParagraph();
            XWPFRun paragraphRun1 = paragraph1.createRun();
            paragraphRun1.setText("
    ");
            paragraph1.setPageBreak(true);
            
            //段落
            XWPFParagraph firstParagraph2 = document.createParagraph();
            XWPFRun run2 = firstParagraph2.createRun();
            run2.setText("BBB");
            run2.setColor("000000");
            run2.setFontSize(10);
            run2.setText("	CCC☑");
            run2.setColor("000000");
            run2.setFontSize(12);
            
           
            OutputStream os =new FileOutputStream("D:/2.docx");
            document.write(os);
            os.flush();
            os.close();
            document.close();
        }
    View Code

    接口返回参考上面execl的改造一下就行了,不赘述了

  • 相关阅读:
    C# MVC跳转
    从字符串中提取数字
    使用Node.js+Socket.IO搭建WebSocket实时应用
    C# 计算当前时间距离今晚00:00:00还有多少分多少秒
    C#错误异常列表
    HTTP请求报文和HTTP响应报文
    Selenium2(webdirver)入门之环境搭建(Java版)
    mysql grant ,User,revoke
    mysql 用drop和delete方法删除用户的区别
    [MySQL]
  • 原文地址:https://www.cnblogs.com/yanan7890/p/6641199.html
Copyright © 2011-2022 走看看