我编写了一个Java程序,将多个excel工作表合并到一个excel中并生成了jar,然后使用java -jar Merge_Excel.jar运行它。
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class Csv_Merge {
public static void main(String[]args){
try{
File folder = new File("c:/test/");
File[] listOfFiles = folder.listFiles();
HSSFWorkbook workbook=new HSSFWorkbook();
for (File file : listOfFiles) {
if (file.isFile()) {
String thisline;
ArrayList<String> al = null;
ArrayList<ArrayList<String>> arlist = new ArrayList<ArrayList<String>>();
HSSFSheet sheet = workbook.createSheet(file.getName());
FileInputStream fis = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
while ((thisline = br.readLine()) != null) {
al = new ArrayList<String>();
String strar[] = thisline.split(",");
for (int j = 0; j < 5; j++) {
for (int k = 1; k < arlist.size(); k++) {
ArrayList<String> ardata = (ArrayList<String>) arlist.get(k);
HSSFRow row = sheet.createRow((short) k);
for (int p = 0; p < ardata.size(); p++) {
HSSFCell cell = row.createCell((short) p);
cell.setCellValue(ardata.get(p).toString());
}
}
al.add(strar[j]);
}
arlist.add(al);
}
fis.close();
FileOutputStream fileOut = new FileOutputStream("c:/test/new.xls");
workbook.write(fileOut);
fileOut.flush();
fileOut.close();
br.close();
}
}
System.out.println("Your excel file has been generated!");
} catch ( Exception ex ) {
System.out.println(ex);
}
}
}
我需要从命令提示符或其他文件(仅是路径)传递excel路径File folder = new File("c:/test/");
的位置和新的合并文件路径FileOutputStream fileOut = new FileOutputStream("c:/test/new.xls");
。
有什么办法做
谢谢
答案 0 :(得分:1)
您可以在运行jar时从命令传递目录路径,并且只需执行以下步骤即可在主Java程序中访问该目录:
1)java -jar程序名.jar c:/ test /
2)
public static void main(String[]args) {
String folderName = args[0];
File folder = new File(folderName);
File[] listOfFiles = folder.listFiles();
}
答案 1 :(得分:0)
使用一种命令行参数将路径传递给main函数,这是一种不错的方法,您应该会很好。