首页 > 解决方案 > 如何在 Apache poi 中使用 java 以 csv 逗号分隔格式编写 excel 文件?

问题描述

我正在尝试使用 apache poi 在 java 中编写一个 excel 文件。我想以 csv 逗号分隔我的 excel 文件格式。我该怎么做 ?这是我现在正在使用的代码-

public class ReadRfdsDump {

    public void readRfdsDump() 
    {
        try
        {

            FileInputStream file = new FileInputStream(new File("C:\\Users\\esatnir\\Videos\\sprint\\sprintvision.sprint.com_Trackor Browser_RF Design Sheet_07062018122740.xlsx"));

            XSSFWorkbook workbook = new XSSFWorkbook(file);

            XSSFSheet sheet = workbook.getSheetAt(0);

            DataFormatter df = new DataFormatter();

            for(int i=0;i<2;i++)
            {
                Row row= sheet.getRow(i);
                System.out.println(df.formatCellValue(row.getCell(1)));
            }

            try {

                FileOutputStream out = new FileOutputStream(new File("C:\\CQ ADD\\Write CQ File\\"+s+".csv"));
                workbook.write(out);
                out.close();
                System.out.println("Excel  has been written successfully on disk.");
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        }
    }
}

我正在使用 .csv 编写 excel 文件,但我不知道它是否是 csv 的正确格式(逗号分隔)?或者我如何以 .csv(逗号分隔)格式编写 excel 文件?

标签: javaexcelstringcollectionsapache-poi

解决方案


在这里您可以找到您的示例以获取更多详细信息,请单击此处

private static final String CVS_SEPERATOR_CHAR=",";
        public static void csvToEXCEL(String csvFileName,String excelFileName) throws Exception{
            checkValidFile(csvFileName);
            BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(csvFileName)));
            HSSFWorkbook myWorkBook = new HSSFWorkbook();
            FileOutputStream writer = new FileOutputStream(new File(excelFileName) );
            HSSFSheet mySheet = myWorkBook.createSheet();
            String line= "";
            int rowNo=0;
            while ( (line=reader.readLine()) != null ){
                String[] columns = line.split(CVS_SEPERATOR_CHAR);// comma seperator
                 HSSFRow myRow =mySheet.createRow(rowNo);
                for (int i=0;i<columns.length;i++){
                    HSSFCell myCell = myRow.createCell(i);
                    myCell.setCellValue(columns[i]);
                }
                 rowNo++;
            }
            myWorkBook.write(writer);
            writer.close();
        }
    private static void checkValidFile(String fileName){
            boolean valid=true;
            try{
                File f = new File(fileName);
                if ( !f.exists() || f.isDirectory() ){
                    valid=false;
                }
            }catch(Exception e){
                valid=false;
            }
            if ( !valid){
                System.out.println("File doesn't exist: " + fileName);
                System.exit(0);
            }
        }

推荐阅读