excel工具类(全)
package com.people2000.common.file;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
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.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
public class ExcelUtils {
private String arr[]=null;
/**
* @info 写出Excel标题
* @param fos
* @return
*/
@SuppressWarnings("resource")
public static void writeExcelTitle(String filePath, String[] ss)
throws IOException {
OutputStream fos = new FileOutputStream(filePath);
HSSFWorkbook xls = new HSSFWorkbook();
HSSFSheet sheet = xls.createSheet();
HSSFRow row = sheet.createRow(0);// 第一行
CellStyle style = setHeadStyleColor(xls);
for (int i = 0; i < ss.length; i++) {
row.createCell(i).setCellValue(ss[i]);
row.getCell(i).setCellStyle(style);
}
xls.write(fos);
fos.close();
}
/**
* @info 写出Excel标题内容
* @param fos
* @return
*/
@SuppressWarnings("resource")
public static byte[] writeExcel(String[] titles,
List
html页面
js控制层
'use strict';
app.controller("communityInfoListListCtrl", [
'$scope',
'$state',
'$stateParams',
'$http',
'FileUploader',
'platformUtil',
'Dic',
function($scope, $state, $stateParams, $http,FileUploader, platformUtil, Dic) {
'use strict';
var EXCELIN = "community/excelin.do";//导入
var LOADING_PIC_PATH = "image/loading.gif";
$scope.pictures = [];
$scope.loadingPath = LOADING_PIC_PATH;
//导入文件文本框变化
var fileBtn = $("input[type=file]");
fileBtn.on("change", function() {
var index = $(this).val().lastIndexOf("\\");
var sFileName = $(this).val().substr((index + 1));
$("#rightText").html(sFileName);
});
/*
* excel批量导入
*
*/
$scope.uploader = new FileUploader({
url: EXCELIN,
autoUpload:true,
removeAfterUpload:true,
});
//添加文件之后
$scope.uploader.onAfterAddingFile = function(fileItem) {
// 格式仅限xls
if ("application/vnd.ms-excel" != fileItem._file.type) {
platformUtil.showAlert('提示', '格式不正确,只能上传.xls格式');
$scope.canUpload = 1;
return false;
}
// 不得大于500K
if (fileItem._file.size > 512000) {
platformUtil.showAlert('提示', '文件超出最大限制,最大限制为500KB');
$scope.canUpload = 1;
return false;
}
$scope.pictures.push({
id:null,
url : LOADING_PIC_PATH,
isDeleted : 0
});
};
//加载当前条目完成回调
$scope.uploader.onCompleteItem = function(fileItem, response, status, headers) {
if(status==200){
//重新获取当前的列表
$scope.getData();
platformUtil.showAlert('提示', '导入成功');
}else{
platformUtil.showAlert('提示', '导入失败');
}
};
java代码controller层
/**批量导入
*
* @param community
* @return
*/
@SuppressWarnings("null")
@RequestMapping(value="/excelin" , method = RequestMethod.POST)
@ResponseBody
private void excelin(HttpServletRequest req,HttpServletResponse res) {
String savePath=req.getSession().getServletContext().getRealPath("WEB-INF/upload");
File saveFileDir=new File(savePath);
if(!saveFileDir.exists()){
//创建临时目录
saveFileDir.mkdirs();
}
//上传时生成临时文件保存目录
String tmpPath=req.getSession().getServletContext().getRealPath("WEB-INF/tmp");
File tmpFile=new File(tmpPath);
if(!tmpFile.exists()){
tmpFile.mkdirs();
}
//消息提示
String message="";
try{
DiskFileItemFactory factory=new DiskFileItemFactory();
factory.setSizeThreshold((1024*10));
factory.setRepository(tmpFile);
ServletFileUpload upload=new ServletFileUpload(factory);
upload.setProgressListener(new ProgressListener() {
//@Override
public void update(long readedBytes, long totalBytes, int currentItem) {
System.out.println("当前已处理:"+readedBytes+totalBytes+currentItem);
}
});
upload.setHeaderEncoding("UTF-8");
if(!ServletFileUpload.isMultipartContent(req)){
return;
}
upload.setFileSizeMax(1024*1024*1);
upload.setSizeMax(1024*1024*10);
@SuppressWarnings("rawtypes")
List items=upload.parseRequest(req);
@SuppressWarnings("rawtypes")
Iterator itr=items.iterator();
while (itr.hasNext()){
FileItem item= (FileItem)itr.next();
if (item.isFormField()){
String name=item.getFieldName();
String value=item.getString("UTF-8");
System.out.println(name+"="+value);
}else {
String fileName=item.getName();
System.out.println("文件名:"+fileName);
if(fileName==null&& fileName.trim().length()==0){
continue;
}
fileName=fileName.substring(fileName.lastIndexOf("\\")+1);
String fileExt=fileName.substring(fileName.lastIndexOf(".")+1).toLowerCase();
System.out.println("上传的文件扩展名是:"+fileExt);
if(!Ext_Nmae.contains(fileExt)){
System.out.println("上传文件扩展是不允许的扩展名:"+fileExt);
message=message+"文件:"+fileName+",上传文件的扩展名是不允许扩展名的:"+fileExt+"
";
break;
}
if(item.getSize()==0) continue;
if(item.getSize()>1024 * 1024 * 1){
System.out.println("上传文件大小:"+item.getSize());
message=message+"文件:"+fileName+",上传文件大小超过限制:"+upload.getFileSizeMax()+"
";
}
String saveFileName=makeFileName(fileName);
InputStream is=item.getInputStream();
FileOutputStream out=new FileOutputStream(savePath+"\\"+saveFileName);
byte buffer[] =new byte[2014];
int len=0;
while ((len=is.read(buffer))>0){
out.write(buffer,0,len);
}
out.close();
is.close();
item.delete();
//开始往数据库中写入东西 path="savePath+"\\"+saveFileName";
String currentPathString=savePath+"\\"+saveFileName;
communityWriteManager.writExcelData(currentPathString);
message=message+"文件:"+fileName+",上传成功
";
}
}
}catch (FileSizeLimitExceededException e){
message=message+"上传文件大小超过限制
";
e.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}
}
private String makeFileName(String fileName){
return UUID.randomUUID().toString().replaceAll("-","")+"_"+fileName;
/*
* 开始往数据中写人excel表格数据 (non-Javadoc)
*
* @see
* com.people2000.mzadmin.business.write.CommunityWriteManager#writExcelData
* ()
*/
@Override
public void writExcelData(String path) throws IOException {
List> readExcelKeyMap = ExcelUtils
.readExcelKeyMap(path);
int temp = -1;
int beanNum=1;
int paramNum=0;
for (Map map : readExcelKeyMap) {
Iterator> iterator = map.entrySet()
.iterator(); // map.entrySet()得到的是set集合,可以使用迭代器遍历
Community community=null;
while (iterator.hasNext()) {
Entry entry = iterator.next();
// key值:副标题 value值:110
// key值:活动编号 value值:110
// key值:作者 value值:110
// key值:微信连接 value值:110
// key值:标题 value值:110
temp =temp+1;
System.out.println("key值:" + entry.getKey() + " value值:"
+ entry.getValue());
if (temp % 5 == 0) {
community = new Community();
beanNum=beanNum+1;
}
if (entry.getKey().equals("作者")) {
community.setAuthor(entry.getValue());
} else if (entry.getKey().equals("副标题")) {
community.setSubtitle(entry.getValue());
} else if (entry.getKey().equals("标题")) {
community.setTitle(entry.getValue());
} else if (entry.getKey().equals("微信连接")) {
community.setWxLinkUrl(entry.getValue());
}else{
}
paramNum=paramNum+1;//为5的倍数就是一列数据填充完成,更新数据库
if((beanNum % 2 ==0)&¶mNum % 5 ==0){//默认第一次创建bean 此时为偶数
communityMapper.insertSelective(community);
}else if(beanNum % 2==1&¶mNum % 5 ==0){//再次创建此时为奇数
communityMapper.insertSelective(community);
}
}
}
}