[Java]如何使CSV内的中文支持EXCEL格式(UTF-8 BOM)

阅读更多

1.EXCEL比较特殊,使用的是UTF-8 BOM的格式,而使用apache Commons csv library用的是UTF-8,会使中文乱码.

 

2.解决办法有二:

核心是写入byte[]的头:{ (byte) 0xEF, (byte) 0xBB, (byte) 0xBF }

第一种是先新建一个文件,写入头,然后再拼接CSVPrinter的内容:

//Add UTF-8 BOM header
			File csvFile = new File(csv_path);
			try {
				fos = new FileOutputStream(csvFile, false);
				fos.write(new byte[] { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF });
				fos.flush();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			//Write CSV
			try (Writer out = new FileWriter(csv_path,true); 
					CSVPrinter printer = new CSVPrinter(out, CSVFormat.EXCEL.withQuote(null).withHeader(
							csvSP.getSearchTime(),searchCriteria
							));
					CSVPrinter printers = new CSVPrinter(out, CSVFormat.EXCEL.withHeader(
							Constant.Col_REQ_ID,Constant.Col_SENDER_DOMAIN,Constant.Col_SENDER,Constant.Col_RECEIVER_DOMAIN,
							Constant.Col_RECIPIENT,Constant.Col_RECIPIENT_IMEI,Constant.Col_RECIPIENT_OPER_CODE,Constant.Col_DIRECTION,
							Constant.Col_CHANNEL,Constant.Col_SUBMIT_TIME,Constant.Col_DELIVER_TIME,Constant.Col_MSG_STATUS,
							Constant.Col_TEXT_CONTENT,Constant.Col_MEDIA_FILE
							))
				) {
				for (CsvModel csv : csvResult) {
					List records = new ArrayList<>();
					records.add(csv.getRequestId());
					records.add(csv.getSenderDomain());
					records.add(csv.getSenderNo());
					printers.printRecord(records);
				}		

 通过new FileWriter(csv_path,true)保持原来内容并拼接.

 

第二种则完全不用Commons,自己拼接:

 

public static void SaveInformativeFile(String content, String Path, String fileName, boolean isFirst) {
		OutputStreamWriter fw = null;
		BufferedWriter writer = null;
		if (content == null || content.equals("")) {
			return;
		}
		try {
			String filepath = Path + File.separator + fileName;
			File informativeFile = new File(filepath);

			FileOutputStream fos = null;
			if (isFirst) {
				fos = new FileOutputStream(informativeFile, false);

				fos.write(new byte[] { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF });
				fos.flush();
			} else {
				fos = new FileOutputStream(informativeFile, true);
			}

			fw = new OutputStreamWriter(fos, "UTF-8");
			writer = new BufferedWriter(fw);
			if (isFirst) {
				String title = "\"" + "ZONE" + "\",\"" + "TACKING ID" + "\",\"" + "CAMPAIGN CD" + "\",\"" + "CHANNEL"
						+ "\",\"" + "SMS SENDER" + "\",\"" + "START DATE" + "\",\"" + "END DATE" + "\",\""
						+ "MESSAGE CODE" + "\"" + "\n";
				writer.write(title);
				writer.flush();
			}

			writer.write(content);
			writer.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (writer != null) {
				try {
					writer.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

 

 

你可能感兴趣的:(csv,format,utf-8,utf-8,bom)