导出csv时,动态改变导出头的是列数及相同数据横行展示

需求:如上图所示:相同的club_id,comp_name、comp_value值打开时Excel展示为一行。 如下图所示

 1059:15条数据,所以加上门店号、门店名称,Excel一共展示32列。这个32列是根据从数据库查询到的数据动态改变的。接下来加上详细代码和解释以及需要注意到的问题。

1:根据实际查询的数据确定需要展示的列数(此处数据是我项目中的实际数量,下边的解释都是我的数据)

说明:dataclubList:是我group by club_id获取的club_id和数量的list集合,这个数量在下边要用到,所以一定要有。

           ClubCountDTO:实体类,用来接收club_id和数量。

因为我的第一、第二列已经确定,所以列数从3、4开始也就是count1=3、count2=4。这个3、4是可以改变的,根据你的需求。

下边的代码时确定列的最大数,并且能够使他按照123456排序。注意此处的问题:如果你也是用map集合,那就要注意map的key的唯一性。他也会展示123456这样的排序,但是他是拿后一个数据覆盖前一个,在实际的导出时是错误的。你也可以写一个main测试类,删除门店名称下边这个for循环,直接在ls里边add集合数据。做一个测试看一下就清楚了。到此动态表头数据添加完成。

//设置表头
boolean containsKey1=false;
boolean containsKey2=false;
int count1=3;
int count2=4;
List<String> ls=new ArrayList<String>();
LinkedHashMap<String, String> titleMap = new LinkedHashMap<String, String>();
titleMap.put("1", "门店号");
titleMap.put("2", "门店名称");
for(ClubCountDTO ccd:dataclubList) {
	ls.add(ccd.getClubCount());
}
String max = Collections.max(ls);
Integer clubsize = Integer.valueOf(max);
for(int i=0;i<clubsize;i++) {
	if(containsKey1 == false && containsKey2 ==false) {
		titleMap.put(String.valueOf(count1), "任务反馈问题"+String.valueOf(count1));
		titleMap.put(String.valueOf(count2), "任务反馈答案"+String.valueOf(count2));
		count2=count2+1;
		count1=count1+1;
	}
	if(containsKey1 == true && containsKey2 ==false) {
		titleMap.put(String.valueOf(count2), "任务反馈问题"+String.valueOf(count2));
		count2=count2+1;
		titleMap.put(String.valueOf(count2), "任务反馈答案"+String.valueOf(count2));
		count2=count2+1;
		count1=count1+1;
	}
	containsKey1 = titleMap.containsKey(String.valueOf(count1));
	containsKey2 = titleMap.containsKey(String.valueOf(count2));
}

2:添加此表头下的数据(看第一张图可以看出我不知道门店是多少个,所以需要动态的判断数据长度把长度不够最大数据长度的补充完整,才能导出数据正常展示。由于我导出工具类型的原因,所有的表头下的数据必须和表头一样长,否则数据展示第一条或者导出失败)。

说明:dataList:从数据库中查询出来要导出来的数据,就是第一张图的数据。

clubIdSet:前置偏移变量;判断前一个和后一个的club_id是否相等

rowSet:确定列的数字,我这个是前两列必须有。所以是2

colSet:好像没有什么关系。这个在短时间做的,没有把冗余代码完全剔除掉。

clubsize:分组后数据的最大值

clubNum:当前club_id的数据值,作用:用来把列数补充到最大列的长度,方便我使用csv工具类导出。

clubsize-clubNum:这个就是当前club_id下数据长度不是最大,要补充的长度。

主要代码:if...else if()....else if()里边,把逻辑弄清楚。

//添加表头数据
List<LinkedHashMap<String, String>> exportData = new ArrayList<LinkedHashMap<String, String>>();

String clubIdSet="";
Integer colSet = 1;
Integer rowSet = 2;
LinkedHashMap<String, String> row = new LinkedHashMap<String, String>();
for(int i =0; i<dataList.size();i++) {
	TaskStoreItemDTO taskStoreItemDTO = dataList.get(i);
		if(!clubIdSet.equals(taskStoreItemDTO.getClubId()) && StringUtils.isBlank(clubIdSet)) {
			row = new LinkedHashMap<String, String>();
			if(StringUtils.isBlank(taskStoreItemDTO.getClubId()) ==false) {
				row.put(String.valueOf(1), taskStoreItemDTO.getClubId());
			}else {
				row.put(String.valueOf(1), "");
			}
			if(StringUtils.isBlank(taskStoreItemDTO.getStoreName()) ==false) {
				row.put(String.valueOf(2), taskStoreItemDTO.getStoreName());
			}else {
						row.put(String.valueOf(2), "");
			}
			clubIdSet = taskStoreItemDTO.getClubId();
			colSet++;
			rowSet = 2;
			if(StringUtils.isBlank(taskStoreItemDTO.getCompName()) == false) {
			    row.put(String.valueOf(++rowSet), taskStoreItemDTO.getCompName());
			}else {
				row.put(String.valueOf(++rowSet), "");
			}
			if(StringUtils.isBlank(taskStoreItemDTO.getCompValue()) ==false) {
				row.put(String.valueOf(++rowSet), taskStoreItemDTO.getCompValue());
			}else {
				row.put(String.valueOf(++rowSet), "");
			}
			exportData.add(row);
			for(ClubCountDTO ccd:dataclubList) {
				if(ccd.getClubId().equals(taskStoreItemDTO.getClubId())) {
					clubNum=Integer.valueOf(ccd.getClubCount());
				}
			}
		}else if(clubIdSet.equals(taskStoreItemDTO.getClubId()) && StringUtils.isBlank(clubIdSet) ==false){
			if(StringUtils.isBlank(taskStoreItemDTO.getCompName()) ==false) {
				row.put(String.valueOf(++rowSet), taskStoreItemDTO.getCompName());
			}else {
				row.put(String.valueOf(++rowSet), "");
			}
			if(StringUtils.isBlank(taskStoreItemDTO.getCompValue()) ==false) {
				row.put(String.valueOf(++rowSet), taskStoreItemDTO.getCompValue());	
			}else {
						row.put(String.valueOf(++rowSet), "");	
			}
		}else if(!clubIdSet.equals(taskStoreItemDTO.getClubId()) && StringUtils.isBlank(clubIdSet) ==false) {
			if(clubNum !=clubsize) {
				boolean containsKey1=true;
				boolean containsKey2=false;
				int count1=rowSet;
				int count2=rowSet+1;
				for(int j=0;j<clubsize-clubNum;j++) {
					row.put(String.valueOf(count2), "");
					count2=count2+1;
					row.put(String.valueOf(count2), "");
					count2=count2+1;
				}
			} 
			row = new LinkedHashMap<String, String>();
			if(StringUtils.isBlank(taskStoreItemDTO.getClubId()) ==false) {
				row.put(String.valueOf(1), taskStoreItemDTO.getClubId());
			}else {
				row.put(String.valueOf(1), "");
			}
			if(StringUtils.isBlank(taskStoreItemDTO.getStoreName()) ==false) {
				row.put(String.valueOf(2), taskStoreItemDTO.getStoreName());
			}else {
				row.put(String.valueOf(2), "");
			}
			clubIdSet = taskStoreItemDTO.getClubId();
			colSet++;
			rowSet = 2;
			if(StringUtils.isBlank(taskStoreItemDTO.getCompName()) == false) {
				row.put(String.valueOf(++rowSet), taskStoreItemDTO.getCompName());
			}else {
				row.put(String.valueOf(++rowSet), "");
			}
			if(StringUtils.isBlank(taskStoreItemDTO.getCompValue()) ==false) {
				row.put(String.valueOf(++rowSet), taskStoreItemDTO.getCompValue());
			}else {
				row.put(String.valueOf(++rowSet), "");
			}
			exportData.add(row);
			for(ClubCountDTO ccd:dataclubList) {
				if(ccd.getClubId().equals(taskStoreItemDTO.getClubId())) {
					clubNum=Integer.valueOf(ccd.getClubCount());
				}
			}
		}
	}

3:csv导出工具类:CSVUtils

public class CSVUtils {
	
	private static CSVUtils csvUtils;
	
	public static CSVUtils getInstance() {
		if (csvUtils == null) {
			csvUtils = new CSVUtils();
		}
		return csvUtils;
	}
	
	 /**
	   * 生成为CVS文件 
	   * @param exportData 
	   *       源数据List 
	   * @param map 
	   *       csv文件的列表头map 
	   * @param outPutPath 
	   *       文件路径 
	   * @param fileName 
	   *       文件名称 
	   * @return 
	   */
	@SuppressWarnings({ "rawtypes","unused" })
	public static String createCSVFile(List exportData, LinkedHashMap map, String outPutPath, String fileName) {
		File csvFile = null;
		BufferedWriter csvFileOutputStream = null;
		String path = null;
		try {
			File file = new File(outPutPath);
			if (!file.exists()) {
				file.mkdirs();
			}
			// 定义文件名格式并创建  
			csvFile = File.createTempFile(fileName, ".csv", new File(outPutPath));
			path = csvFile.getCanonicalPath();
			// System.out.println(csvFile.getName());
			// System.out.println("csvFile:" + path);
			// UTF-8使正确读取分隔符","  osw.write(new String(new byte[] { (byte) 0xEF, (byte) 0xBB,(byte) 0xBF }));   
			// 如果生产文件乱码,windows下用gbk,linux用UTF-8
			csvFileOutputStream = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(csvFile), "UTF-8"), 1024);
			csvFileOutputStream.write('\ufeff');
			
			// 写入文件头部
			for (Iterator propertyIterator = map.entrySet().iterator(); propertyIterator.hasNext();) {
				java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator.next();
				csvFileOutputStream.write((String) propertyEntry.getValue() != null ? (String) propertyEntry.getValue() : "");
				
				if (propertyIterator.hasNext()) {
					csvFileOutputStream.write(",");
				}
			}
			
			csvFileOutputStream.newLine();
			
			// 写入文件内容  
			for (Iterator iterator = exportData.iterator(); iterator.hasNext();) {
				Object row = (Object) iterator.next();
				for (Iterator propertyIterator = map.entrySet().iterator(); propertyIterator.hasNext();) {
					java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator.next();
					// csvFileOutputStream.write((String) BeanUtils.getProperty(row, (String) propertyEntry.getValue() != null ? (String) propertyEntry.getValue() : ""));
					csvFileOutputStream.write((String) BeanUtils.getProperty(row, (String) propertyEntry.getKey()));
					
					if (propertyIterator.hasNext()) {
						csvFileOutputStream.write(",");
					}
				}
				
				if (iterator.hasNext()) {
					csvFileOutputStream.newLine();
				}
			}
			
			csvFileOutputStream.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				csvFileOutputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return csvFile.getName();
	}
		
//  /**
//   * 生成为CVS文件 
//   * @param exportData 
//   *       源数据List 
//   * @param map 
//   *       csv文件的列表头map 
//   * @param outPutPath 
//   *       文件路径 
//   * @param fileName 
//   *       文件名称 
//   * @return 
//   */
//	@SuppressWarnings({ "rawtypes","unused" })
//	public static String createCSVFile(List exportData, LinkedHashMap map, String outPutPath, String fileName) {
//		File csvFile = null;
//		BufferedWriter csvFileOutputStream = null;
//		String path = null;
//		try {
//			File file = new File(outPutPath);
//			if (!file.exists()) {
//				file.mkdir();
//			}
//			// 定义文件名格式并创建  
//			csvFile = File.createTempFile(fileName, ".csv", new File(outPutPath));
//			path = csvFile.getCanonicalPath();
			System.out.println(csvFile.getName());
			System.out.println("csvFile:" + path);
//			// UTF-8使正确读取分隔符","  osw.write(new String(new byte[] { (byte) 0xEF, (byte) 0xBB,(byte) 0xBF }));   
//			// 如果生产文件乱码,windows下用gbk,linux用UTF-8
//			// csvFileOutputStream = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(csvFile), "GBK"), 1024);
//			CsvWriter csvWriter = new CsvWriter(csvFile.getAbsolutePath(), ',', Charset.forName("UTF-8"));
//			// csvWriter.write(new String(new byte[] { (byte) 0xEF, (byte) 0xBB,(byte) 0xBF }));
//			String chatset = new String(new byte[] { (byte) 0xEF, (byte) 0xBB,(byte) 0xBF });
//			
//			String[] titleArray = new String[map.size()];
//			// 写入文件头部
//			int i = 0;
//			for (Iterator propertyIterator = map.entrySet().iterator(); propertyIterator.hasNext();) {
//				java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator.next();
//				// csvFileOutputStream.write('\ufeff');
//				// csvFileOutputStream.write((String) propertyEntry.getValue() != null ? (String) propertyEntry.getValue() : "");
//				// csvWriter.write((String) propertyEntry.getValue() != null ? (String) propertyEntry.getValue() : "");
//				if (i == 0) {
//					titleArray[i++] = (String) propertyEntry.getValue() != null ? chatset + (String) propertyEntry.getValue() : "";
//				}
//				else {
//					titleArray[i++] = (String) propertyEntry.getValue() != null ? (String) propertyEntry.getValue() : "";
//				}
//				
				if (propertyIterator.hasNext()) {
					// csvFileOutputStream.write(",");
					// csvWriter.write(",");
				}
//			}
//			
//			csvWriter.writeRecord(titleArray, true);
//			
//			
//			// csvFileOutputStream.newLine();
//			// csvWriter.write("\r\n");
//			
//			// 写入文件内容  
//			for (Iterator iterator = exportData.iterator(); iterator.hasNext();) {
//				Object row = (Object) iterator.next();
//				String[] datdaArray = new String[map.size()];
//				i = 0;
//				for (Iterator propertyIterator = map.entrySet().iterator(); propertyIterator.hasNext();) {
//					java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator.next();
//					// csvFileOutputStream.write('\ufeff');
//					// csvFileOutputStream.write((String) BeanUtils.getProperty(row, (String) propertyEntry.getKey()));
//					// csvWriter.write((String) BeanUtils.getProperty(row, (String) propertyEntry.getKey()));
//					datdaArray[i++] = (String) BeanUtils.getProperty(row, (String) propertyEntry.getKey());
//					
					if (propertyIterator.hasNext()) {
						// csvFileOutputStream.write(",");
						// csvWriter.write(",");
					}
//				}
//				
//				csvWriter.writeRecord(datdaArray, true);
//				
				if (iterator.hasNext()) {
					// csvFileOutputStream.newLine();
					// csvWriter.write("\r\n");
				}
//			}
//			
//			
//			// csvFileOutputStream.flush();
//			csvWriter.close();
//		} catch (Exception e) {
//			e.printStackTrace();
//		} finally {
			try {
				csvFileOutputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
//		}
//		return csvFile.getName();
//	}

	/**
	 *  下载文件    
	 *  @param response     
	 *  @param csvFilePath   
	 *  文件路径    
	 *  @param fileName      
	 *   文件名称     
	 *  @throws IOException   
	 *  
	 */
	public static void exportFile(HttpServletResponse response, String csvFilePath, String fileName) throws IOException {
		response.setContentType("application/csv;charset=UTF-8");
		response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));

		InputStream in = null;
		try {
			in = new FileInputStream(csvFilePath);
			int len = 0;
			byte[] buffer = new byte[1024];
			response.setCharacterEncoding("UTF-8");
			OutputStream out = response.getOutputStream();
			while ((len = in.read(buffer)) > 0) {
				out.write(new byte[] { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF });
				out.write(buffer, 0, len);
			}
		} catch (FileNotFoundException e) {
			//System.out.println(e);
		} finally {
			if (in != null) {
				in.close();
			}
		}
	}
	
	 /**
     * 生成csv文件之前特殊字符转义
     * @param str
     * @return
     */
    public static String csvString(String str){
    	str=str.toString().replaceAll("[/r/n]"," ");
        if(str.contains("-")){
            str = str.replace("\"","\"\"");
            str ="\"" + str + "\"";
        }
        return str;
    }
	 /** 
	   * 测试数据 
	   * @param args 
	   */ 
	@SuppressWarnings({ "rawtypes", "unchecked" }) 
	public static void main(String[] args) { 
			List exportData = new ArrayList<Map>(); 
			Map row1 = new LinkedHashMap<String, String>(); 
			row1.put("1", "11"); 
			row1.put("2", "12"); 
			row1.put("3", "13"); 
			row1.put("4", "14"); 
			exportData.add(row1); 
			row1 = new LinkedHashMap<String, String>(); 
			row1.put("1", "21"); 
			row1.put("2", "22"); 
			row1.put("3", "23"); 
			row1.put("4", "24萨范德萨费迪"); 
			exportData.add(row1); 
			
			LinkedHashMap map = new LinkedHashMap(); 
			//设置列名
			map.put("1", "第一列-名称"); 
			map.put("2", "第二列名称"); 
			map.put("3", "第三列名称"); 
			map.put("4", "第四列名称"); 
			//这个文件上传到路径,可以配置在数据库从数据库读取,这样方便一些!
			String path = "C:/wpapi/"; 
			
			//文件名=生产的文件名称+时间戳
			String fileName = "文件导出"; 
//			String createCSVFile = CSVUtils.createCSVFile(exportData, map, path, fileName); 
//			System.out.println("文件名称:" + createCSVFile);
			
			String str = "";
		//	System.out.println("aa===" + str.length());
		} 
}

本博客仅支持大家学习交流技术用,禁止使用在其他用途上,对于使用在其他用途上及产生的后果不承担任何责任,本博客的最终解释权归本人所有。欢迎大家学习交流。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值