poi-java基础操作

首先 导入jar包,用的maven

 1 <dependency>
 2     <groupId>org.apache.poi</groupId>
 3     <artifactId>poi</artifactId>
 4     <version>3.9</version>
 5 </dependency>
 6 
 7 <dependency>
 8     <groupId>org.apache.poi</groupId>
 9     <artifactId>poi-ooxml</artifactId>
10     <version>3.9</version>
11 </dependency>

接着就是poi的基本操作,做到可以输出来,表格的样式操作比较麻烦虽然不难,所以不做介绍,程序生成的文档能看不就行了。哈哈哈

@Test
    public void print() throws IOException{
        //设置查询条件
        Factory factory = new Factory();
        factory.setState(1);
        List<Factory> dataList = FactoryMapper.find(factory);
        String[] title = new String[]{"厂家全称","缩写","联系人","电话","手机","传真","备注"};
        Workbook wb=new HSSFWorkbook();//创建工作簿
        Sheet sheet=wb.createSheet();//创建工作簿SHEET
        
        
        Row nRow = sheet.createRow(0);//新建行对象
        Cell nCell=null;
        for (int i = 0; i < title.length; i++) {
            nCell = nRow.createCell(i);//新建第0行的第I个单元格对象
            nCell.setCellValue(title[i]);//单元格赋值
        }
        
        //写数据
        int nrow=1;    
        int ncell=0;
        for(int j=0;j<dataList.size();j++){
            ncell=0;
            //初始化
            Factory f = dataList.get(j);//获取到每条厂家记录
            
            //初始化是第二行开始,所以row应该是初始1,用完再自加
            nRow = sheet.createRow(nrow++);
            nRow.setHeightInPoints(21);
            
            //第1个单元格开始,所以cell是0,用完自加
            nCell = nRow.createCell(ncell++);
            nCell.setCellValue(f.getFullName());
            
            nCell = nRow.createCell(ncell++);
            nCell.setCellValue(f.getFactoryName());
            
            nCell = nRow.createCell(ncell++);
            nCell.setCellValue(f.getContractor());
            
            nCell = nRow.createCell(ncell++);
            nCell.setCellValue(f.getPhone());
            
            nCell = nRow.createCell(ncell++);
            nCell.setCellValue(f.getMobile());
            
            nCell = nRow.createCell(ncell++);
            nCell.setCellValue(f.getFax());
            
            nCell = nRow.createCell(ncell++);
            nCell.setCellValue(f.getCnote());
        }

        //输出路径
        FileOutputStream  fos=new FileOutputStream(new File("G://a.xls"));
        //wb写入流
        wb.write(fos);
        //输出流刷新再关闭
        fos.flush();
        fos.close();
    }

注意 输出的文件名只能是xls结尾的!