java - 如何在 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 文件?
解决方案
在这里您可以找到您的示例以获取更多详细信息,请单击此处
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);
}
}
推荐阅读
- bash - 在 for 循环中:将不同的字符串格式附加到 bash 中的变量
- laravel - Laravel Gate 自定义响应
- sql-server - How do I resolve a SQL-Server query not Recognising whitespace characters?
- ios - Google assistant: Account linking - OAuth authorization code flow on IOS
- machine-learning - Modeling Churn (supervised vs. unsupervised)
- c# - Dapper INSERT AccessViolationException
- r - r:错误:替换参数为零长度
- python - Pandas - 只读每行的前几行
- reactjs - React Redux - 在调度下一个操作之前等待异步 api 调用完成
- python - 使用 python 和 tkcalendar 时更改日期格式