csv格式转换xls

来源:互联网 发布:mac修改hosts文件翻墙 编辑:程序博客网 时间:2024/03/29 21:19
/**  * 将excel文件由csv格式转换为xls格式 * @author hanchuang  * */public class CSVToExcelConverter {public static void CSVToExcel(String filename,String url) throws IOException {ArrayList arList = null;ArrayList al = null;String fName = url+filename;String thisLine;int count = 0;FileInputStream fis = new FileInputStream(fName);DataInputStream myInput = new DataInputStream(fis);int i = 0;arList = new ArrayList();while ((thisLine = myInput.readLine()) != null) {al = new ArrayList();String strar[] = thisLine.split(",");for (int j = 0; j < strar.length; j++) {al.add(strar[j]);}arList.add(al);System.out.println();i++;}try {HSSFWorkbook hwb = new HSSFWorkbook();HSSFSheet sheet = hwb.createSheet("new sheet");for (int k = 0; k < arList.size(); k++) {ArrayList ardata = (ArrayList) arList.get(k);HSSFRow row = sheet.createRow((short) 0 + k);for (int p = 0; p < ardata.size(); p++) {HSSFCell cell = row.createCell((short) p);//String data = ardata.get(p).toString();// getBytes(String charsetName): 使用指定的字符集将字符串编码为 byte 序列,并将结果存储到一个新的 byte 数组中。String data = new String(ardata.get(p).toString().getBytes("ISO-8859-1"), "gbk");if (data.startsWith("=")) {cell.setCellType(Cell.CELL_TYPE_STRING);data = data.replaceAll("\"", "");data = data.replaceAll("=", "");cell.setCellValue(data);} else if (data.startsWith("\"")) {data = data.replaceAll("\"", "");cell.setCellType(Cell.CELL_TYPE_STRING);cell.setCellValue(data);} else {data = data.replaceAll("\"", "");cell.setCellType(Cell.CELL_TYPE_NUMERIC);cell.setCellValue(data);}// */// cell.setCellValue(ardata.get(p).toString());}}String[] fNames=filename.split("csv");String newFilename="";System.out.println(fNames.length);for(int n=0;n<fNames.length;n++){newFilename=fNames[0];}FileOutputStream fileOut = new FileOutputStream(url+newFilename+"xls");hwb.write(fileOut);fileOut.close();System.out.println("Your excel file has been generated");} catch (Exception ex) {ex.printStackTrace();} }}


原创粉丝点击