csv格式轉換xls

/** 
 * 將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();
		} 
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章