package com.ninemax.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.jdom.DocType;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

import com.ninemax.model.Question;

public class CreateFilesWaysUtil {
	
	/**
	 * 单位缩进字符串。
	 */
	private static String SPACE = "   ";
	
	/**
	 * 创建Excel
	 * 
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("all")
	public static void createExcelFile(List<Question> list) throws Exception {
		// 1.创建一个workbook,对应一个Excel文件
		HSSFWorkbook wb = new HSSFWorkbook();
		// 2.在workbook中添加一个sheet,对应Excel文件中的sheet
		HSSFSheet sheet = wb.createSheet("Question");
		// 3.在sheet中添加表头第0行
		HSSFRow row = sheet.createRow((int) 0);
		// 4.创建单元格,并且设置表头,设置表头居中
		HSSFCellStyle style = wb.createCellStyle();
		// 4.1格式居中
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		// 4.2单元格信息设置
		HSSFCell cell = row.createCell((short) 0);
		cell.setCellValue("ID");
		cell.setCellStyle(style);
		cell = row.createCell((short) 1);
		cell.setCellValue("CONTENT");
		cell.setCellStyle(style);
		cell = row.createCell((short) 2);
		cell.setCellValue("ROLE");
		cell.setCellStyle(style);
		cell = row.createCell((short) 3);
		cell.setCellValue("CORE_ONE");
		cell.setCellStyle(style);
		cell = row.createCell((short) 4);
		cell.setCellValue("CORE_TWO");
		cell.setCellStyle(style);

		// 5.写入实体数据
		for (int i = 0; i < list.size(); i++) {

			row = sheet.createRow((int) i + 1);

			Question q = (Question) list.get(i);

			// 4.3单元格信息值填写
			row.createCell((short) 0).setCellValue(q.getId());
			row.createCell((short) 1).setCellValue(q.getContent());
			row.createCell((short) 2).setCellValue(Integer.valueOf(q.getRole()));
			row.createCell((short) 3).setCellValue(q.getCode_one());
			row.createCell((short) 4).setCellValue(q.getCode_two());
		}
		
		FileOutputStream fous = new FileOutputStream(ConstantUtil.FILE_PATH +  ConstantUtil.File_TYPE_XLS);
		wb.write(fous);
		fous.close();
	}
	
	public static void createCsvFile(List<Question> list) {
		// 表格头
		Object[] head = { "ID", "CONTENT", "ROLE", "CODE_ONE", "CODE_TWO" };
		List<Object> headList = Arrays.asList(head);
		// 数据
		List<List<Object>> dataList = new ArrayList<List<Object>>();
		List<Object> rowList = null;
		for (Question q : list) {
			rowList = new ArrayList<Object>();
			rowList.add(q.getId());
			rowList.add(q.getContent());
			rowList.add(q.getRole());
			rowList.add(q.getCode_one());
			rowList.add(q.getCode_two());
			dataList.add(rowList);
		}
		// 文件名称
		String fileName = ConstantUtil.File_TYPE_CSV;
		// 文件路径
		String filePath = ConstantUtil.FILE_PATH; 

		File csvFile = null;
		BufferedWriter csvWtriter = null;
		try {
			csvFile = new File(filePath + fileName);
			File parent = csvFile.getParentFile();
			if (parent != null && !parent.exists()) {
				parent.mkdirs();
			}
			csvFile.createNewFile();
			// GB2312使正确读取分隔符","
			csvWtriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(csvFile), "GB2312"), 1024);
			int num = headList.size() / 2;
			StringBuffer buffer = new StringBuffer();
			for (int i = 0; i < num; i++) {
				buffer.append(" ,");
			}
			csvWtriter.write(buffer.toString() + fileName + buffer.toString());
			csvWtriter.newLine();
			// 写入文件头部
			writeRow(headList, csvWtriter);
			// 写入文件内容
			for (List<Object> row : dataList) {
				writeRow(row, csvWtriter);
			}
			csvWtriter.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				csvWtriter.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static void createXmlFile(List<Question> list) throws Exception {
		// 生成XML文档对象
		Document doc = new Document();
		// 生成XM文档根节点
		Element root = new Element("Questions");
		// 文档头声明
		doc.addContent(new DocType("ChineseQuestions", "WPRIM_2.dtd"));
		// 根节点添加到文档中
		doc.addContent(root);
		//生成子节点
		for (Question q : list) {
			Element question= new Element("Question");
			question.addContent(new Element("Id").setText(q.getId()));
			question.addContent(new Element("Content").setText(q.getContent()));
			question.addContent(new Element("Role").setText(String.valueOf(q.getRole())));
			question.addContent(new Element("Code_One").setText(q.getCode_one()));
			question.addContent(new Element("Code_Two").setText(q.getCode_two()));
			root.addContent(question);
		}
		XMLOutputter XMLOut = new XMLOutputter(Format.getPrettyFormat());  
        XMLOut.output(doc, new FileOutputStream(ConstantUtil.FILE_PATH + ConstantUtil.File_TYPE_XML));
	}
	
	public static void createJsonFile(List<Question> list) throws Exception {

		JSONObject jsonObj = new JSONObject();// 创建json格式的数据

		JSONArray jsonArr = new JSONArray();// json格式的数组

		JSONObject jsonObjArr = new JSONObject();

		for (Question q : list) {
			jsonObjArr.put("id", q.getId());
			jsonObjArr.put("content", q.getContent().toString());
			jsonObjArr.put("role", q.getRole());
			jsonObjArr.put("code_one", q.getCode_one());
			jsonObjArr.put("code_two", q.getCode_two());
			jsonArr.add(jsonObjArr);// 将json格式的数据放到json格式的数组里
		}
		jsonObj.put("Questions", jsonArr);// 再将这个json格式的的数组放到最终的json对象中。
		
		FileWriter fw = null;
		PrintWriter out = null ;
		try {
			fw = new FileWriter(ConstantUtil.FILE_PATH + ConstantUtil.File_TYPE_JSON);
			out = new PrintWriter(fw);
			out.write(formatJson(jsonObj.toString()));
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			// 关闭流
		    try {
				fw.close();
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		  
		}
	}
	
	public static void createHtmlFile(List<Question> list) {

		StringBuilder sb = new StringBuilder();

		sb.append("<html>\n\t");
		sb.append("<head>\n\t");
		sb.append("<title>Questions</title>\n\t");
		sb.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=gb23122\" />\n\t");
		sb.append("<style type=\"text/css\">\n\t");
		sb.append("TABLE{border-collapse:collapse;border-left:solid 1 #000000; border-top:solid 1 #000000;padding:5px;}\n\t");
		sb.append("TH{border-right:solid 1 #000000;border-bottom:solid 1 #000000;}\n\t");
		sb.append("TD{font:normal;border-right:solid 1 #000000;border-bottom:solid 1 #000000;}\n\t");
		sb.append("</style>\n\t</head>\n\t");
		sb.append("<body bgcolor=\"#FFF8DC\">\n\t");
		sb.append("<div align=\"center\">\n\t");
		sb.append("<table border=\"1\">\n\t");
		sb.append("<tr>\n\t");
		sb.append("<th>ID</th>\n\t");
		sb.append("<th>Content</th>\n\t");
		sb.append("<th>Role</th>\n\t");
		sb.append("<th>Code_One</th>\n\t");
		sb.append("<th>Code_Two</th>\n\t");
		sb.append("</tr>\n\t");
		for (Question q : list) {
			sb.append("<tr>\n\t");
			sb.append("<td>");
			sb.append(q.getId());
			sb.append("</td>\n\t");
			sb.append("<td>");
			sb.append(q.getContent());
			sb.append("</td>\n\t");
			sb.append("<td>");
			sb.append(q.getRole());
			sb.append("</td>\n\t");
			sb.append("<td>");
			sb.append(q.getCode_one());
			sb.append("</td>\n\t");
			sb.append("<td>");
			sb.append(q.getCode_two());
			sb.append("</td>\n\t");
			sb.append("</tr>\n\t");
		}
		sb.append("</table>");
		sb.append("\n\t</div>\n\t</body>\n\t</html>");
		FileWriter fw = null;
		PrintWriter out = null ;
		try {
			fw = new FileWriter(ConstantUtil.FILE_PATH + ConstantUtil.File_TYPE_HTML);
			out = new PrintWriter(fw);
			out.write(sb.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			// 关闭流
		    try {
				fw.close();
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		  
		}
	}
	
	/**
	 * 返回格式化JSON字符串。
	 * 
	 * @param json  未格式化的JSON字符串。
	 *           
	 * @return 格式化的JSON字符串。
	 */
	private static String formatJson(String json) {
		
		StringBuffer result = new StringBuffer();

		int length = json.length();
		int number = 0;
		char key = 0;

		// 遍历输入字符串。
		for (int i = 0; i < length; i++) {
			// 1、获取当前字符。
			key = json.charAt(i);

			// 2、如果当前字符是前方括号、前花括号做如下处理:
			if ((key == '[') || (key == '{')) {
				// (1)如果前面还有字符,并且字符为“:”,打印:换行和缩进字符字符串。
				if ((i - 1 > 0) && (json.charAt(i - 1) == ':')) {
					result.append('\n');
					result.append(indent(number));
				}

				// (2)打印:当前字符。
				result.append(key);

				// (3)前方括号、前花括号,的后面必须换行。打印:换行。
				result.append('\n');

				// (4)每出现一次前方括号、前花括号;缩进次数增加一次。打印:新行缩进。
				number++;
				result.append(indent(number));

				// (5)进行下一次循环。
				continue;
			}

			// 3、如果当前字符是后方括号、后花括号做如下处理:
			if ((key == ']') || (key == '}')) {
				// (1)后方括号、后花括号,的前面必须换行。打印:换行。
				result.append('\n');

				// (2)每出现一次后方括号、后花括号;缩进次数减少一次。打印:缩进。
				number--;
				result.append(indent(number));

				// (3)打印:当前字符。
				result.append(key);

				// (4)如果当前字符后面还有字符,并且字符不为“,”,打印:换行。
				if (((i + 1) < length) && (json.charAt(i + 1) != ',')) {
					result.append('\n');
				}

				// (5)继续下一次循环。
				continue;
			}

			// 4、如果当前字符是逗号。逗号后面换行,并缩进,不改变缩进次数。
//			if ((key == ',')) {
//				result.append(key);
//				result.append('\n');
//				result.append(indent(number));
//				continue;
//			}

			// 5、打印:当前字符。
			result.append(key);
		}
		
		return result.toString();
	}

	/**
	 * 返回指定次数的缩进字符串。每一次缩进三个空格,即SPACE。
	 * 
	 * @param number 缩进次数
	 * @return 指定缩进次数的字符串
	 */
	private static String indent(int number) {
		StringBuffer result = new StringBuffer();
		for (int i = 0; i < number; i++) {
			result.append(SPACE);
		}
		return result.toString();
	}
	
	/**
	 * 写一行数据
	 * 
	 * @param row 数据列表
	 * @param csvWriter
	 * @throws IOException
	 */
	private static void writeRow(List<Object> row, BufferedWriter csvWriter)throws IOException {
		
		for (Object data : row) {
			StringBuffer sb = new StringBuffer();
			String rowStr = sb.append("\"").append(data).append("\",").toString();
			csvWriter.write(rowStr);
		}
		csvWriter.newLine();
	}
	
}

文件路径+文件名称

public class ConstantUtil {
	
	public static final String FILE_PATH = "F:/apache-tomcat-8/webapps/CQAC/resources/file/";

	public static final String File_TYPE_XLS = "question.xls";

	public static final String File_TYPE_CSV = "question.csv";

	public static final String File_TYPE_XML = "question.xml";

	public static final String File_TYPE_HTML = "question.html";

	public static final String File_TYPE_JSON = "question.json";

}

需要引入的JAR

<!-- Excel -->
		<dependency>
		    <groupId>org.apache.poi</groupId>
		    <artifactId>poi</artifactId>
		    <version>3.7</version>
		</dependency>
		<!-- XML -->
		<dependency>
		    <groupId>jdom</groupId>
		    <artifactId>jdom</artifactId>
		    <version>1.0</version>
		</dependency>
		<!-- JSON -->
		<dependency>
		    <groupId>net.sf.json-lib</groupId>
		    <artifactId>json-lib</artifactId>
		    <version>2.4</version>
		    <classifier>jdk15</classifier><!--指定jdk版本-->  
		</dependency>
		<dependency>
		    <groupId>net.sf.ezmorph</groupId>
		    <artifactId>ezmorph</artifactId>
		    <version>1.0.6</version>
		</dependency>
		<dependency>
		    <groupId>commons-lang</groupId>
		    <artifactId>commons-lang</artifactId>
		    <version>2.6</version>
		</dependency>
		<dependency>
		    <groupId>commons-beanutils</groupId>
		    <artifactId>commons-beanutils</artifactId>
		    <version>1.9.3</version>
		</dependency>
企鹅群:260052172(只斗图,不研究技术)