Java POI写Excel

Java POI 输出Excel文件时中文乱码的问题,解决办法如下:

    public void importExcel() {
        File myFile = new File("F:/GITHUB/333.xls");
        InputStream inStream;
        try {
            // 读取文件流
            inStream = new FileInputStream(myFile);
            // Excel 文件
            HSSFWorkbook wookbook = new HSSFWorkbook(inStream);
            //
            HSSFSheet hssfSheet = wookbook.getSheet("Sheet1");
            for (int i = 1; i < hssfSheet.getLastRowNum() + 1; i++) {
                //
                HSSFRow hssfRow = hssfSheet.getRow(i);
                if (hssfRow == null) {
                    continue;
                } else {
                    //
                    HSSFCell cell = hssfRow.getCell((short) 3);
                    if (cell == null) {
                        cell = hssfRow.createCell((short) 3);
                    }
                    cell.setEncoding(HSSFCell.ENCODING_UTF_16); //设置好编码格式就好了
                    cell.setCellValue("中文乱码吗");
                }
            }
            // 输出流
            FileOutputStream out = null;
            try {
                out = new FileOutputStream("F:/GITHUB/3335.xls");
                // 输出
                wookbook.write(out);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            System.out.println("文件不存在");
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            System.out.println("文件读取错误");
            e.printStackTrace();
        }
    }

 

posted @ 2016-10-20 17:11  小严  阅读(181)  评论(0)    收藏  举报