poi操作excel初步

来源:互联网 发布:平板电脑软件大全 编辑:程序博客网 时间:2024/06/03 08:20

一. 使用poi导出excel表格

public class PoiWriteTest {    public static void main(String[] args) {        String[] title = new String[]{"id","name", "gender"};        HSSFWorkbook workbook = new HSSFWorkbook(); //建立工作簿        HSSFSheet sheet = workbook.createSheet(); //创建表单        HSSFRow row = sheet.createRow(0); //创建一行        for(int i = 0; i < title.length; i++)        {            Cell cell = row.createCell(i);            cell.setCellValue(title[i]);        }        for(int i=1; i < 5; i++)        {            HSSFRow row1 = sheet.createRow(i);            Cell cell1 = row1.createCell(0);            cell1.setCellValue(i);            cell1 = row1.createCell(1);            cell1.setCellValue("user"+i);            cell1 = row1.createCell(2);            cell1.setCellValue("man");        }        File file = new File("E://poi_test.xls");        try{            file.createNewFile();            FileOutputStream fos = new FileOutputStream(file);            workbook.write(fos);//在硬盘生成excel表格            fos.close();        }catch (Exception ex)        {            ex.printStackTrace();        }    }}

二. 使用poi导入excel数据

public class PoiReadTest {    public static void main(String[] args) {        try {            File file = new File("e:\\poi_test.xls");            HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(file));            HSSFSheet sheet = workbook.getSheet("sheet0");            for (int i = 0; i < sheet.getLastRowNum(); i++)            {                HSSFRow row = sheet.getRow(i);                for(int j = 0; j < row.getLastCellNum(); j++)                {                    Cell cell = row.getCell(j);                    if(j == 0)                    {                        cell.setCellType(Cell.CELL_TYPE_STRING);                    }                    String value = cell.getStringCellValue();                    System.out.print(value+" ");                }                System.out.println();            }        }catch (Exception ex)        {            ex.printStackTrace();        }    }}

设置excel cell背景色

网上流传的一种方式这样的,如下所示:

HSSFCellStyle style = workbook.createCellStyle();style.setFillBackgroundColor(HSSFColor.AQUA.index);cell.setCellStyle(style);

但是代码执行完后,是没有效果的。
下面是一种有效的方式

HSSFCellStyle style = wb.createCellStyle();style.setFillForegroundColor(IndexedColors.AQUA.getIndex());style.setFillPattern(CellStyle.SOLID_FOREGROUND);cells.setCellStyle(style);
0 0
原创粉丝点击