Java Xml export Excel file, Java Excel export tool class, Java export Excel tool class

Java Xml export Excel file, Java Excel export tool class, Java export Excel tool class

 

===========================

©Copyright Sweet Potato Yao September 13, 2017

http://fanshuyao.iteye.com/

 

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletOutputStream;

import org.apache.commons.lang.StringUtils;

public class ExportUtil {

	/**
	 * Only export properties included in includeFieldNames
	 * @param sheetName the name of the lower left corner of the sheet
	 * @param firstRowTitle The title that needs to be set in the first row, if it is empty, it will not be set
	 * @param list the set of data to display
	 * @param headers table attribute column name array
	 * @param includeFieldNames contains entity properties
	 * @param widths The width of the column, if not set (null), the default is set, and the setting is set according to the corresponding column width (can be one, can be the corresponding number, an integer number, such as 200)
	 * @param outputStream The stream object associated with the output device, which can export the EXCEL document to a local file or network
	 * @param datetimePattern time format, when empty (Null or empty string), the default is yyyy-MM-dd HH:mm:ss
	 * @throws Exception
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public <T> void exportExcel(String sheetName, String firstRowTitle, List<T> list, String[] headers, String[] includeFieldNames, Integer[] widths,
			ServletOutputStream outputStream, String datetimePattern) throws Exception {
		
		// default output format
		if (StringUtils.isBlank(datetimePattern)) {
			datetimePattern = "yyyy-MM-dd HH:mm:ss";
		}
		
		//Create an excel application file
		StringBuffer sb = new StringBuffer();
		sb.append("<?xml version=\"1.0\"?>");
		sb.append("\n");
		sb.append("<?mso-application progid=\"Excel.Sheet\"?>");
		sb.append("\n");
		sb.append("<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"");
		sb.append("\n");
		sb.append(" xmlns:o=\"urn:schemas-microsoft-com:office:office\"");
		sb.append("\n");
		sb.append(" xmlns:x=\"urn:schemas-microsoft-com:office:excel\"");
		sb.append("\n");
		sb.append(" xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\"");
		sb.append("\n");
		sb.append(" xmlns:html=\"http://www.w3.org/TR/REC-html40\">");
		sb.append("\n");
		
		sb.append("<Styles>\n");
		
		/* Set the column header style */
		sb.append("<Style ss:ID=\"header\" ss:Name=\"header\">\n");//ss:ID=“header”对应下面的Row ss:StyleID=“header”
		sb.append("<Interior ss:Color=\"#c4d79b\" ss:Pattern=\"Solid\"/>\n");// Set background color
		sb.append("<Font ss:FontName=\"微软雅黑\" x:CharSet=\"134\" ss:Bold=\"Bolder\" ss:Size=\"12\"/>\n");//设置字体
		sb.append("</Style>\n");
		
		/*Other default style settings*/
		sb.append("<Style ss:ID=\"Default\" ss:Name=\"Normal\">\n");
		//sb.append("<Alignment ss:Vertical=\"Center\"/>\n");
		sb.append("<Alignment ss:Horizontal=\"Center\" ss:Vertical=\"Center\" ss:WrapText=\"1\"/>\n");// Left, middle and right settings, one is horizontal, one is vertical
		sb.append("<Borders>\n");
		sb.append("<Border ss:Position=\"Left\" ss:LineStyle=\"Continuous\" ss:Color=\"#666\" ss:Weight=\"1\"/>\n");//左边框设置
		sb.append("<Border ss:Position=\"Right\" ss:LineStyle=\"Continuous\" ss:Color=\"#666\" ss:Weight=\"1\"/>\n");//右边框设置
		sb.append("<Border ss:Position=\"Bottom\" ss:LineStyle=\"Continuous\" ss:Color=\"#666\" ss:Weight=\"1\"/>\n");//下边框设置
		sb.append("<Border ss:Position=\"Top\" ss:LineStyle=\"Continuous\" ss:Color=\"#666\" ss:Weight=\"1\"/>\n");//上边框设置
		sb.append("</Borders>\n");
		sb.append("<Font ss:FontName=\"宋体\" x:CharSet=\"134\" ss:Size=\"12\"/>\n");
		sb.append("<Interior/>\n");
		sb.append("<NumberFormat/>\n");
		sb.append("<Protection/>\n");
		sb.append("</Style>\n");
		
		sb.append("</Styles>\n");
		
		try {
			
			// generate table
			int headersLength = headers.length;
			
			sb.append("<Worksheet ss:Name=\"" + sheetName + "\">");
			sb.append("\n");
			sb.append("<Table ss:ExpandedColumnCount=\"" + headersLength
					+ "\" ss:ExpandedRowCount=\"1000000\" x:FullColumns=\"1\" x:FullRows=\"1\">");
			sb.append("\n");
			
			if(!StrUtils.isEmptyArray(widths)){
				if(widths.length > 1){
					for (int i = 0; i < headersLength; i++) {
						sb.append("<Column ss:AutoFitWidth=\"0\" ss:Width=\""+widths[i]+"\"/>");
					}
				}else{
					for (int i = 0; i < headersLength; i++) {
						sb.append("<Column ss:AutoFitWidth=\"0\" ss:Width=\""+widths[0]+"\"/>");
					}
				}
			}
			
			
			// output the title of the first line
			if(!StrUtils.isBlank(firstRowTitle)){
				//ss:StyleID can add row or Cell, add it to Row, the whole row (including empty Cell) has it, add Cell, only Cell has it.
				sb.append("<Row  ss:Height=\"30\">");
				sb.append("<Cell ss:StyleID=\"header\" ss:MergeAcross=\""+ (headersLength - 1)+"\"><Data ss:Type=\"String\">" + firstRowTitle + "</Data></Cell>");
				sb.append("</Row>");
			}
			
			// output column header
			sb.append("<Row>");
			for (int i = 0; i < headersLength; i++) {
				sb.append("<Cell ss:StyleID=\"header\"><Data ss:Type=\"String\">" + headers[i] + "</Data></Cell>");
			}
			sb.append("</Row>");
			
			// Build table body data
			for (int j = 0; j < list.size(); j++) {
				
				sb.append("<Row>");
				
				T t = (T) list.get(j);
				
				for (int i = 0; i < includeFieldNames.length; i++) {
					
					// get property name
					String fieldName = includeFieldNames[i];
					
					String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
					
					// get the class object
					Class tCls = t.getClass();
					
					// get property value
					Object value = null;
					
					try {
						// get the class method
						Method getMethod = tCls.getMethod(getMethodName, new Class[] {});
						
						// get property value
						value = getMethod.invoke(t, new Object[] {});
						
					} catch (NoSuchMethodException e) {
						// continue the loop
						continue;
					}
					
					// Cast the type after judging the type of the value
					String textValue = "";
					if (value instanceof Integer) {
						// int value = ((Integer) value).intValue();
						textValue = value.toString();
					} else if (value instanceof String) {
						// String s = (String) value;
						textValue = value.toString();
					} else if (value instanceof Double) {
						// double d = ((Double) value).doubleValue();
						textValue = String.format("%.2f", value);
					} else if (value instanceof Float) {
						// float f = ((Float) value).floatValue();
						textValue = value.toString();
					} else if (value instanceof Long) {
						// long l = ((Long) value).longValue();
						textValue = value.toString();
					} else if (value instanceof Boolean) {
						// boolean b = ((Boolean) value).booleanValue();
						textValue = value.toString();
					} else if (value instanceof Date) {
						Date date = (Date) value;
						SimpleDateFormat sdf = new SimpleDateFormat(datetimePattern);
						textValue = sdf.format(date);
					} else if ((value instanceof BigDecimal)) {
						textValue = value.toString();
					} else {
						if (value != null) {
							continue;
						}
					}
					
					sb.append("<Cell><Data ss:Type=\"String\">");
					
					// If it is not image data, use regular expressions to determine whether textValue consists of numbers
					if (StringUtils.isNotBlank(textValue)) {
						
						Pattern p = Pattern.compile("^//d+(//.//d+)?$");
						Matches matches = p.matches (textValue);
						if (matcher.matches()) {
							// is a number treated as a double
							sb.append(Double.parseDouble(textValue));
						} else {
							sb.append(textValue);
						}
						
					}
					
					sb.append("</Data></Cell>");
					
				}
				
				sb.append("</Row>");
				sb.append("\n");
				
			}
			
			sb.append("</Table>");
			sb.append("<WorksheetOptions xmlns=\"urn:schemas-microsoft-com:office:excel\">");
			sb.append("\n");
			sb.append("<ProtectObjects>False</ProtectObjects>");
			sb.append("\n");
			sb.append("<ProtectScenarios>False</ProtectScenarios>");
			sb.append("\n");
			sb.append("</WorksheetOptions>");
			sb.append("\n");
			sb.append("</Worksheet>");
			sb.append("</Workbook>");
			sb.append("\n");
			
		} catch (SecurityException e) {
			e.printStackTrace ();
		} catch (IllegalArgumentException e) {
			e.printStackTrace ();
		} catch (IllegalAccessException e) {
			e.printStackTrace ();
		} catch (InvocationTargetException e) {
			e.printStackTrace ();
		}
		
		try {
			outputStream.write(sb.toString().getBytes());
			outputStream.flush();
			outputStream.close();
			sb = null;
		} catch (IOException e) {
			e.printStackTrace ();
		} finally {
			try {
				outputStream.close();
			} catch (IOException e) {
				e.printStackTrace ();
			}
		}
	}

	

}

 

How to use:

@RequestMapping("/exportMsCard")
	public void exportMsCard(HttpServletRequest req, HttpServletResponse res,
			Integer pageIndex, Integer pageSize,
			String cardNo, String mobile, String cinemaBaseName, Date startDate, Date endDate) {
		try {
			if(endDate != null){
				endDate = DateUtils.dateAdd(endDate, 1, false);
			}
			List<MsCard> msCards = msCardService.list(pageIndex, pageSize,
					cardNo, mobile, cinemaBaseName, startDate, endDate);
			
			String[] headers = { "Membership Card Number", "Member Nickname", "Mobile Number", "Cinema Name", "Creation Time"};
			String[] includeFieldNames = { "cardNo", "nickname", "mobile", "cinemaBaseName", "createTime"};
			// set file suffix and encode
			String fileName = new String("Operation platform-membership card package-membership card list.xls".getBytes("UTF-8"), "iso8859-1");
			// Set the encoding of the response;
			res.setCharacterEncoding("gb2312");
			res.setHeader("Content-disposition", "attachment; filename=" + fileName);
			res.setContentType("application/msexcel;charset=UTF-8");
			// Export order to Excel
			ExportUtil exportUtil = new ExportUtil();
			exportUtil.exportExcel("sheet", "", msCards, headers, includeFieldNames, new Integer[]{200}, res.getOutputStream(), null);
		} catch (Exception e) {
			e.printStackTrace ();
		}
	}

 Note: It cannot be requested directly through Ajax, it needs to be submitted through a form.

 

Attributes used to convert Excel in xml mode:



 

Add one:

ss:MergeAcross means merging across columns, as follows:

sb.append("<Row  ss:Height=\"30\">");
sb.append("<Cell ss:StyleID=\"header\" ss:MergeAcross=\""+ (headersLength - 1)+"\"><Data ss:Type=\"String\">" + firstRowTitle + "</Data></Cell>");
sb.append("</Row>");

 Pay attention to whether you need to subtract 1, because it means how many columns are spanned, that is, to merge other columns, excluding yourself, so you need to subtract 1

 

All-purpose method:

If you suddenly need to add some unknown attributes, you can first create an Excel file, make a template, and then save it as an Xml file. Note that it is an Xml file. After saving, open the Xml file to see how some attributes of the template you created should be set up. But the opened xml file is messy, so find the corresponding grid by searching.

 

=============================

©Copyright Sweet Potato Yao September 13, 2017

http://fanshuyao.iteye.com/

 

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326812124&siteId=291194637