我正在尝试使用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文件??
答案 0 :(得分:1)
在这里您可以找到更多示例的示例click here
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);
}
}