<repo_name>longyt/Maven_Projects<file_sep>/BackStage/src/com/shadow/Utils/ExcelUtils.java
package com.shadow.Utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor.HSSFColorPredefined;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CellType;

import com.shadow.Utils.Entity.BaseEntity;
import com.shadow.Utils.Entity.Contain;

public class ExcelUtils {
	private static Short red=(Short) HSSFColorPredefined.RED.getIndex();
	private static Short green=(Short) HSSFColorPredefined.GREEN.getIndex();
	private static Short blur=(Short) HSSFColorPredefined.BLUE.getIndex();
	private static Short white=(Short) HSSFColorPredefined.WHITE.getIndex();
	
	/**
	 * 导出数据
	 * @throws Exception 
	 */
	public static void Export(List<BaseEntity> list,HttpServletRequest resuest,Class clazz) throws Exception{
		

		
		Class.forName("com.shadow.Utils.Entity.Contain");
		
		HSSFWorkbook hssfWorkbook= new HSSFWorkbook();
		
		HSSFSheet hssfSheet = hssfWorkbook.createSheet();//拿到第一幅
		
		HSSFRow OneRow = hssfSheet.createRow(0);//拿到第一行
		
		HSSFCell  OneCell= OneRow.createCell(0, CellType.STRING);
		
		CustomFontAndBackgroundColor(hssfWorkbook,OneCell,blur,(short) 30);//设置字体颜色
		
		OneCell.setCellValue("导出"+clazz.getSimpleName()+"表中的数据");
		
		//拿到标题
		HSSFRow TitleRow = hssfSheet.createRow(1);
		
		int TitleRowIndex=0;
		for (int i = 0; i < Contain.list.size(); i++) {
			HSSFCell TitleCell = TitleRow.createCell(TitleRowIndex, CellType.STRING);
			TitleCell.setCellValue((String) Contain.list.get(i).get("title"+(i+1)));
			TitleRowIndex++;
		}
			
		
		//拿到标题下的数据
		int RowIndex=2;
		for (BaseEntity entity : list) {
			HSSFRow DataRow = hssfSheet.createRow(RowIndex);
			int CellIndex=0;
			Class clabb = entity.getClass();
			Field [] fields = clabb.getDeclaredFields();
			for (Field field : fields) {
				field.setAccessible(true);
				if(field.getType().getSimpleName().equals("Integer")){
					Integer Tempvalue = (Integer) field.get(entity);
					DataRow.createCell(CellIndex, CellType.NUMERIC).setCellValue(Tempvalue);
				}else{
					String Tempvalue = (String) field.get(entity);
					DataRow.createCell(CellIndex, CellType.STRING).setCellValue(Tempvalue);
				}
				CellIndex++;
			}
			RowIndex++;
		}
		
		
		
		String ExportPath = resuest.getServletContext().getRealPath("//export");
		File file=new File(ExportPath);
		if(!file.exists()){
			file.mkdirs();
		}
		Contain.ExportResurcePath=ExportPath;
		
		System.out.println(ExportPath);
		
		File ExportFile = new File(Contain.ExportResurcePath+"//"+clazz.getSimpleName()+".xls");
		OutputStream fos=new FileOutputStream(ExportFile);
		hssfWorkbook.write(fos);
		if(!ExportFile.exists()){
			ExportFile.createNewFile();
		}
		fos.flush();
		fos.close();
		hssfWorkbook.close();
	}
	
	
	public static List<BaseEntity> Import(String ImportFileName,Class clazz) throws Exception{
		
		/**
		 * 定义一个list
		 */
		List<BaseEntity> list=new ArrayList<>();
		
		File file=new File(ImportFileName);
		InputStream in=new FileInputStream(file);
		HSSFWorkbook hssfWorkbook=new HSSFWorkbook(in);//拿到xls文件
		
		int sheets = hssfWorkbook.getNumberOfSheets();
		for (int i = 0; i < sheets; i++) {
			HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(i);
			HSSFRow OneRow = hssfSheet.createRow(0);
			int OneRowCells = OneRow.getLastCellNum();
			if(OneRowCells>1){
				System.out.println("格式错误");
			}else{
				HSSFRow TwoRow = hssfSheet.getRow(1);
				int TwoRowCells = TwoRow.getLastCellNum();
				for (int j = 0; j < TwoRowCells; j++) {
					String TitleName = TwoRow.getCell(j).getStringCellValue();
					if(TitleName.equals(Contain.list.get(j).get("title"+(j+1)))){
						//System.out.println("模板正确");
					}else{
						System.out.println("模板错误");
					}
				}
			}
			
			/**
			 * 遍历有多少行遍历所有数据放入list中返回
			 */
			int AllRows = hssfSheet.getLastRowNum();
			for (int j = 2; j <= AllRows; j++) {
					if(j%3==0){
						Thread.sleep(1000);
					}
				HSSFRow Row = hssfSheet.getRow(j);
				int Allcells = Row.getLastCellNum();
				BaseEntity entity2 = (BaseEntity) clazz.newInstance();
				for (int k = 0; k < Allcells; k++) {
					HSSFCell cell = Row.getCell(k);
					String FieldName = (String) Contain.list.get(k).get("name"+(k+1));
					Field field = clazz.getDeclaredField(FieldName);
					field.setAccessible(true);
					
					if(cell.getCellTypeEnum()==CellType.NUMERIC){
						Integer Tempvalue = (int) cell.getNumericCellValue();
						if(field.getType().getSimpleName().equals("Integer")){
							field.set(entity2, Tempvalue);
						}else if(field.getType().getSimpleName().equals("String")){
							field.set(entity2, Tempvalue.toString());
						}
					}else if(cell.getCellTypeEnum()==CellType.STRING){
						String Tempvalue = (String)cell.getStringCellValue();
						if(field.getType().getSimpleName().equals("Integer")){
							field.set(entity2, Tempvalue);
						}else if(field.getType().getSimpleName().equals("String")){
							field.set(entity2, Tempvalue.toString());
						}
					}
					
				}
				Contain.percent=((j*1.0)/(AllRows*1.0))*100;
				list.add(entity2);
				
			}//遍历数据for循环结束
			
		}//遍历sheet循环结束
		
		return list;
	}
	
		//字体颜色大小设置
		public static void CustomFontAndBackgroundColor(HSSFWorkbook hssfWorkbook,HSSFCell hssfCell,Short color,Short fontsize){
					//设置背景颜色
					CellStyle cellStyle = hssfWorkbook.createCellStyle();
					//cellStyle.setFillBackgroundColor(HSSFColorPredefined.RED.getIndex());
					short alignCenter = CellStyle.VERTICAL_TOP;
					cellStyle.setAlignment(alignCenter);
					hssfCell.setCellStyle(cellStyle);
					//设置字体颜色和大小
					HSSFFont hssfFont = hssfWorkbook.createFont();
					hssfFont.setColor(color);
					hssfFont.setFontHeightInPoints(fontsize);
					cellStyle.setFont(hssfFont);
		}

}
<file_sep>/BackStage/src/com/shadow/Utils/Servlet/UploadServlet.java
package com.shadow.Utils.Servlet;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.shadow.Utils.Entity.Data;

@WebServlet("/upload.do")
public class UploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Data data=new Data();
		request.setCharacterEncoding("utf-8");
		String boundary=request.getContentType();
		boundary ="--"+boundary.substring(boundary.indexOf("=")+1, boundary.length())+"--";
		int boundaryLen = boundary.getBytes("iso-8859-1").length;
		int contentLength=request.getContentLength();
		DataInputStream di =new DataInputStream(request.getInputStream());
		FileOutputStream fos =null;
		byte[] body = new byte[5000];
		int totalReadSize =0;
		String filePath ="";
		String suffix="";
		String fileName="";
		String oldfilename="";
		String fullfilename="";
		int k =0;
		while(totalReadSize<contentLength){
			//读取
			int readSize=di.read(body, 0, 5000);
			totalReadSize+=readSize;
			String content = new String(body,"iso-8859-1");
			int contentTypeIndex = content.indexOf("Content-Type");
			int flag =0;
			//写入文件
			if(k==0){//第一次读
				//把读取到的内容转换成为字符串
				//因为读取到的内容本身为字节
				//因为内容的头部包含了各种文件的信息（包括文件名和文件后缀）
				int fileNameIndex = content.indexOf("filename");
				//获取contentTypeIndex的位置是为了方便找出文件的后缀
				
				//suffixContet，整个文件名
				String suffixContet = content.substring(fileNameIndex, contentTypeIndex);
				data.setFullSongName(suffixContet);
				fullfilename=suffixContet;
				//截取出文件后缀
				int pointerIndex = suffixContet.lastIndexOf(".");
				suffix = suffixContet.substring(pointerIndex, suffixContet.length()-3);
				//拿到点之前的内容
				oldfilename = suffixContet.substring(0,pointerIndex);
				data.setSongName(oldfilename);
				//通过系统当前时间生成一个唯一的文件名 
				SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
				fileName =sdf.format(new Date())+suffix;
				//找出头部的无用内容
				//并且计算出这个无用内容的长度（字节的长度）;
				int pos = content.indexOf("\n", contentTypeIndex);
				pos =  content.indexOf("\n", pos+1);
				String disableContent = content.substring(0, pos);
				int start = disableContent.getBytes("iso-8859-1").length;
				//request.getSession().getServletContext() web的上下文（webroot的路径）
				filePath = request.getSession().getServletContext().getRealPath("/resource")+"\\"+fileName;
				File file = new File(filePath);
				file.createNewFile();
				
				flag=content.indexOf(boundary, contentTypeIndex);
				fos = new FileOutputStream(file);
	
				if(flag>0){//一次性读完了
					fos.write(body, start+1, readSize-(start+boundaryLen+4));
					
				}else{
					fos.write(body, start+1, readSize-(start+1));
					fos.flush();
					body = new byte[5000];
				}
			}else{
				flag = content.indexOf(boundary, contentTypeIndex);
				if(flag<0){
					fos.write(body, 0, readSize);
					fos.flush();
					body = new byte[5000];
				}else{
					fos.write(body, 0, readSize-(boundaryLen+4));
				}
			}
			
			k++;
		}
		fos.flush();
		fos.close();
		di.close();
		
		//,\"oldfilename\":\""+oldfilename+"\",\"suffixContet\":\""+fullfilename+"\"
		response.getWriter().write("{\"success\":\"success\",\"path\":\""+fileName+"\"}");
		
	}

}
