java导入导出excel常用操作小结及简单示例

POI中常用设置EXCEL的操作小结:

操作excel如下

HSSFWorkbook wb = new HSSFWorkbook();  //创建一个webbook,对应一个Excel文件

HSSFSheet sheet = wb.createSheet();    //添加一个sheet,对应Excel文件中的sheet 构造方法可以有参也可以无参wb.createSheet("学生表一")

HSSFRow row = sheet.createRow((int) 0);  //sheet的第一行

HSSFCell cell = row.createCell(0);     //某行的第一列
cell.setCellValue("学号");             //添加值

HSSFCellStyle style = wb.createCellStyle();       //创建样式   

1.设置背景色:
style.setFillForegroundColor((short) 10);// 设置背景色为红色  参数也可用(HSSFColor.RED.index)
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

2.设置边框:
style.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框
style.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框
style.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框

3.设置居中:
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 垂直居中
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 水平居中      

4.设置字体:
style.setFont(font);//字体格式

HSSFFont font = wb.createFont();
font.setFontName("黑体");
font.setFontHeightInPoints((short) 16);//设置字体大小
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//粗体显示

5.设置列宽:
sheet.setColumnWidth(0, 10000); //第一个参数代表列,第2个参数代表宽度值

6.设置自动换行:
setBorder.setWrapText(true);//设置自动换行

7.合并单元格:
Region region1 = new Region(0, (short) 0, 0, (short) 6);   //参数1:起始行号 参数2:起始列号 参数3:终止行号 参数4:终止列号

8.下拉列表(序列):
String[] textlist = (String[]) moudlMap.get(mkey);  
DVConstraint constraint = DVConstraint.createExplicitListConstraint(textlist);  
// 设置数据有效性加载在哪个单元格上,四个参数分别是:起始行、终止行、起始列、终止列  
CellRangeAddressList regions = new CellRangeAddressList(1,1000, Integer.parseInt(mkey.toString()), Integer.parseInt(mkey.toString()));  
// 数据有效性对象  
HSSFDataValidation data_validation_list = new HSSFDataValidation(regions, constraint);  
sheet.addValidationData(data_validation_list);


public class exportexcel  
{  
    /**
     * @功能:java导出Excel
     */  
    private static List<StudentTest> getStudentTest() throws Exception  
    {  
        List list = new ArrayList();  
        SimpleDateFormat df = new SimpleDateFormat("yyyy-mm-dd");  
        StudentTest user1 = new StudentTest(1, "张三", 16, df.parse("1997-03-12"));  
        StudentTest user2 = new StudentTest(2, "李四", 17, df.parse("1996-08-12"));  
        StudentTest user3 = new StudentTest(3, "王五", 26, df.parse("1985-11-12"));  
        list.add(user1);  
        list.add(user2);  
        list.add(user3);  
        return list;  
    }  
    public static void main(String[] args) throws Exception  
    {  
        // 第一步,创建一个webbook,对应一个Excel文件  
        HSSFWorkbook wb = new HSSFWorkbook();  
        // 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet  
        HSSFSheet sheet = wb.createSheet("学生表一");  
        // 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short  
        HSSFRow row = sheet.createRow((int) 0);  
        // 第四步,创建单元格,并设置值表头 设置表头居中  
        HSSFCellStyle style = wb.createCellStyle();  
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式  
        HSSFCell cell = row.createCell(0);  
        cell.setCellValue("学号");  
        cell.setCellStyle(style);  
        cell = row.createCell(1);  
        cell.setCellValue("姓名");  
        cell.setCellStyle(style);  
        cell = row.createCell(2);  
        cell.setCellValue("年龄");  
        cell.setCellStyle(style);  
        cell = row.createCell(3);  
        cell.setCellValue("生日");  
        cell.setCellStyle(style);  
        // 第五步,写入实体数据 实际应用中这些数据从数据库得到,  
        List list = exportexcel.getStudentTest();  
        for (int i = 0; i < list.size(); i++)  
        {  
            row = sheet.createRow((int) i + 1);  
            StudentTest stu = (StudentTest) list.get(i);  
            // 第四步,创建单元格,并设置值  
            row.createCell(0).setCellValue((double) stu.getId());  
            row.createCell(1).setCellValue(stu.getName());  
            row.createCell(2).setCellValue((double) stu.getAge());  
            cell = row.createCell(3);  
            cell.setCellValue(new SimpleDateFormat("yyyy-mm-dd").format(stu  
                    .getBirth()));  
        }  
        // 第六步,将文件存到指定位置  
        try  {  
            String path="F:"+File.separator;
            String name="Student";
            System.out.println(path+name+".xls");
            File exportfile=new File(path+name+".xls");
            FileOutputStream fout = new FileOutputStream(exportfile);             
            wb.write(fout);  
            fout.close();  
        } catch (Exception e)  {  
            e.printStackTrace();  
        }  
    }  
}


--------------------------------------------------------------------------------
public class importexcel {
    /**
     * @功能:java导入Excel
     */
    public static String filePath = "F:/Student.xls";
    public static void main(String[] args) {
        try {
            // 创建对Excel工作簿文件的引用
            HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(filePath));
            // 在Excel文档中,第一张工作表的缺省索引是0
            HSSFSheet sheet = workbook.getSheetAt(0);
            //HSSFSheet sheet = workbook.getSheet("学生表一");
            //获取到Excel文件中的所有行数
            int rows = sheet.getPhysicalNumberOfRows();
            //获取所有内容
            String value="";
            //遍历行
            for (int i = 0; i < rows; i++) {
                // 读取第i行
                HSSFRow row = sheet.getRow(i);    
                if (row != null) {
                    //获取到Excel文件中的所有的列
                    int cells = row.getPhysicalNumberOfCells();
                    //遍历列
                    for (int j = 0; j < cells; j++) {
                        //获取每列的值
                        HSSFCell cell = row.getCell(j);
                        if (cell != null) {
                            switch (cell.getCellType()) {
                                case HSSFCell.CELL_TYPE_FORMULA:
                                break;
                                case HSSFCell.CELL_TYPE_NUMERIC:
                                value += cell.getNumericCellValue() + ",";        
                                break;  
                                case HSSFCell.CELL_TYPE_STRING:
                                value += cell.getStringCellValue() + ",";
                                break;
                                default:
                                value += "0";
                                 break;                            
                        }
                    }
                }
            }
                value+=" ";
        }
            System.out.println(value);
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

原文地址:https://www.cnblogs.com/cajx/p/4224007.html