週末閒來無事就先把Java導入導出的整理出來html
1、導出excel模板(只是建立excel格式,供別人填寫,我剛學的方法還比較笨,但願諒解哈,之後有比較好的再補上)spring
1.1 代碼以下 個人都是應用於springmvc的示例json
public class ExcelView extends AbstractExcelView {mvc
String [] list={"男","女"};//生成的excel模板,對於性別就有下拉框能夠選擇了app
@Overrideide
protected void buildExcelDocument(Map<String, Object> model, HSSFWorkbook workbook, HttpServletRequest request, HttpServletResponse response) throws Exception {oop
//To change body of implemented methods use File | Settings | File Templates.post
HSSFSheet hssfSheet = workbook.createSheet("客戶基本信息");ui
hssfSheet.setDefaultColumnWidth(20);// 設置的每一列的默認寬度this
HSSFCell hssfCell = getCell(hssfSheet,0,0);//聲明第一行第一列
hssfCell.setCellType(HSSFCell.CELL_TYPE_STRING);//該單元格的類型爲String
setText(hssfCell,"客戶名稱");//該單元格的文本
hssfCell = getCell(hssfSheet,0,1);
hssfCell.setCellType(HSSFCell.CELL_TYPE_STRING);
setText(hssfCell,"省(福建省)");
hssfCell = getCell(hssfSheet,0,2);
hssfCell.setCellType(HSSFCell.CELL_TYPE_STRING);
setText(hssfCell,"市(廈門市)");
hssfCell = getCell(hssfSheet,0,3);
hssfCell.setCellType(HSSFCell.CELL_TYPE_STRING);
setText(hssfCell,"區/懸");
hssfCell = getCell(hssfSheet,0,4);
hssfCell.setCellType(HSSFCell.CELL_TYPE_STRING);
setText(hssfCell,"公司名稱");
hssfSheet.setColumnWidth(4, 30);
hssfCell = getCell(hssfSheet,0,5);
hssfCell.setCellType(HSSFCell.CELL_TYPE_STRING);
setText(hssfCell,"公司詳細地址");
hssfSheet.setColumnWidth(5, 100);
hssfCell = getCell(hssfSheet,0,6);
hssfCell.setCellType(HSSFCell.CELL_TYPE_STRING);
setText(hssfCell, "職工人數");
hssfCell = getCell(hssfSheet,0,7);
hssfCell.setCellType(HSSFCell.CELL_TYPE_STRING);
setText(hssfCell,"所屬行業");
hssfSheet.setColumnWidth(7,50);
hssfCell = getCell(hssfSheet,0,8);
hssfCell.setCellType(HSSFCell.CELL_TYPE_STRING);
setText(hssfCell,"所屬社區");
hssfCell = getCell(hssfSheet,0,9);
hssfCell.setCellType(HSSFCell.CELL_TYPE_STRING);
setText(hssfCell,"登記人姓名");
hssfCell = getCell(hssfSheet,0,10);
hssfCell.setCellType(HSSFCell.CELL_TYPE_STRING);
CellRangeAddressList regions = new CellRangeAddressList(0,1000,10,10);
DVConstraint constraint = DVConstraint.createExplicitListConstraint(list);//建立下拉選擇
HSSFDataValidation data_validation = new HSSFDataValidation(regions,constraint);
hssfSheet.addValidationData(data_validation);
setText(hssfCell, "登記人性別");
hssfCell = getCell(hssfSheet,0,11);
hssfCell.setCellType(HSSFCell.CELL_TYPE_STRING);
setText(hssfCell,"***號");
hssfCell = getCell(hssfSheet,0,12);
hssfCell.setCellType(HSSFCell.CELL_TYPE_STRING);
setText(hssfCell,"生日");
hssfCell = getCell(hssfSheet,0,13);
hssfCell.setCellType(HSSFCell.CELL_TYPE_STRING);
setText(hssfCell,"戶籍");
hssfCell = getCell(hssfSheet,0,14);
hssfCell.setCellType(HSSFCell.CELL_TYPE_STRING);
setText(hssfCell,"學歷");
hssfCell = getCell(hssfSheet,0,15);
hssfCell.setCellType(HSSFCell.CELL_TYPE_STRING);
setText(hssfCell,"畢業院校");
hssfCell = getCell(hssfSheet,0,16);
hssfCell.setCellType(HSSFCell.CELL_TYPE_STRING);
setText(hssfCell,"政治面貌");
hssfCell = getCell(hssfSheet,0,17);
hssfCell.setCellType(HSSFCell.CELL_TYPE_STRING);
setText(hssfCell,"手機號碼");
hssfCell = getCell(hssfSheet,0,18);
hssfCell.setCellType(HSSFCell.CELL_TYPE_STRING);
setText(hssfCell,"電話號碼");
hssfCell = getCell(hssfSheet,0,19);
hssfCell.setCellType(HSSFCell.CELL_TYPE_STRING);
setText(hssfCell,"郵箱");
hssfCell = getCell(hssfSheet,0,20);
hssfCell.setCellType(HSSFCell.CELL_TYPE_STRING);
setText(hssfCell,"郵編");
hssfCell = getCell(hssfSheet,0,21);
hssfCell.setCellType(HSSFCell.CELL_TYPE_STRING);
setText(hssfCell,"傳真");
hssfCell = getCell(hssfSheet,0,22);
hssfCell.setCellType(HSSFCell.CELL_TYPE_STRING);
setText(hssfCell,"愛好");
hssfCell = getCell(hssfSheet,0,23);
hssfCell.setCellType(HSSFCell.CELL_TYPE_STRING);
setText(hssfCell,"職位");
hssfCell = getCell(hssfSheet,0,24);
hssfCell.setCellType(HSSFCell.CELL_TYPE_STRING);
setText(hssfCell,"加入的社團或組織");
hssfCell = getCell(hssfSheet,0,25);
hssfCell.setCellType(HSSFCell.CELL_TYPE_STRING);
setText(hssfCell,"工做經歷");
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition", "p_w_upload;filename=" + URLEncoder.encode("客戶基本信息模板.xls","utf-8"));
OutputStream ouputStream = response.getOutputStream();
workbook.write(ouputStream);
ouputStream.flush();
ouputStream.close();
}
}
Controller下的代碼:
@RequestMapping(value = "download_template_excel.do")
public ModelAndView downLoadTemplateExcel(ModelMap modelMap){
ExcelView excelView = new ExcelView();
return new ModelAndView(excelView);
//若是咱們也要傳數據過去也是能夠的,只須要將查詢出來的LIST放在modelMap裏面,而後經過new ModelAndView(excelView,modelMap)將數據傳給excelView,在該類裏面進行數據添加就能夠了。
}
2、導入excel並解析獲得數據
目前作的文件上傳是直接點擊button按鈕就能夠選擇文件上傳,經過iframe嵌入上傳文件的表單
所引用的JS文件:
(function($) {
var noop = function(){ return true; };
var frameCount = 0;
$.uploadDefault = {
url: '',
fileName: 'filedata',
dataType: 'json',
params: {},
onSend: noop,
onComplate: noop
};
$.upload = function(options) {
var opts = $.extend(jQuery.uploadDefault, options);
if (opts.url == '') {
return;
}
var canSend = opts.onSend();
if (!canSend) {
return;
}
var frameName = 'upload_frame_' + (frameCount++);
var iframe = $('<iframe style="position:absolute;top:-9999px" />').attr('name', frameName);
var form = $('<form method="post" style="display:none;" enctype="multipart/form-data" />').attr('name', 'form_' + frameName);
form.attr("target", frameName).attr('action', opts.url);
// form中增長數據域
var formHtml = '<input type="file" name="' + opts.fileName + '">';
for (key in opts.params) {
formHtml += '<input type="hidden" name="' + key + '" value="' + opts.params[key] + '">';
}
form.append(formHtml);
iframe.appendTo("body");
form.appendTo("body");
// iframe 在提交完成以後
iframe.load(function() {
var contents = $(this).contents().get(0);
var data = $(contents).find('body').html();
var first = data.indexOf("{");
var last = data.lastIndexOf("}");
data = data.substring(first,last+1);
if ('json' == opts.dataType) {
data = window.eval('(' + data + ')');
}
opts.onComplate(data);
setTimeout(function() {
iframe.remove();
form.remove();
}, 5000);
});
// 文件框
var fileInput = $('input[type=file][name=' + opts.fileName + ']', form);
fileInput.change(function() {
form.submit();
});
fileInput.click();
};
})(jQuery);
頁面的JS:
function doImportExcel(){
$.upload({
url:"import_crmCustBas.json",
params:{},
onComplate:function(data){
doSearch();
ChtUtil.getMessage().show("導入成功...");
}
});
}
action:
@RequestMapping(value = "import_crmCustBas.json",method = RequestMethod.POST)
public ModelMap importExcel(ModelMap modelMap,MultipartHttpServletRequest request)throws IOException, BasException {
List<MultipartFile> files = request.getFiles("filedata");
if(files!=null){
for (MultipartFile file : files) {
InputStream in = file.getInputStream();
//解析Excel
crmCustBasServiceImpl.importExcel(in);
}
}
modelMap = SpringModelTools.convertAjaxSuccess(modelMap);
return modelMap;
}
service:
public boolean importExcel(InputStream inputStream)throws IOException, BasException {
boolean flag = true;
List<Map<String,String>> list = UtilExcel.resolveExcel("custName,provinceId,cityId,townId,enterpriseName,enterpriseAddress,countEmployer,industry,community,username,sex,idCardNo,birthday,houseHold,degreeEducation,graduateSchool, politics,mobilePhone,phone,email,zip,chuanZhen,enjoy,position,joinOrgnise,workExperience", inputStream, 0, new HashMap<String,String>(), 1);
if(list.size()>0){
for(Map<String,String> map :list){
CrmCustBas crmCustBas = new CrmCustBas();
for(String key:map.keySet()){
if("custName".equals(key)){
crmCustBas.setCustName(map.get(key));
}else if("provinceId".equals(key)){
BsmArea bsmAreaProvinceId = basDao.queryOne(BsmArea.class,"name",map.get(key));
if(bsmAreaProvinceId!=null){
crmCustBas.setProvinceId(bsmAreaProvinceId.getId());
}else {
crmCustBas.setProvinceId("0");
}
}else if("cityId".equals(key)){
BsmArea bsmAreaCityId = basDao.queryOne(BsmArea.class,"name",map.get(key));
if(bsmAreaCityId!=null){
crmCustBas.setCityId(bsmAreaCityId.getId());
}else {
crmCustBas.setCityId("0");
}
}else if("townId".equals(key)){
BsmArea bsmAreaTownId = basDao.queryOne(BsmArea.class,"name",map.get(key));
if(bsmAreaTownId!=null){
crmCustBas.setTownId(bsmAreaTownId.getId());
}else {
crmCustBas.setTownId("0");
}
}else if("countEmployer".equals(key)){
String count = map.get(key);
Integer countEmployer = Integer.parseInt(count);
crmCustBas.setCountEmployer(countEmployer);
}else if("community".equals(key)){
crmCustBas.setCommunity(map.get(key));
}else if("username".equals(key)){
crmCustBas.setUsername(map.get(key));
}else if("sex".equals(key)){
if("男".equals(map.get(key))){
crmCustBas.setSex("0");
}else {
crmCustBas.setSex("1");
}
}else if("idCardNo".equals(key)){
crmCustBas.setIdCardNo(map.get(key));
}else if("birthday".equals(key)){
String str = map.get(key);
Date birthday = UtilDate.parseDate(str);
crmCustBas.setBirthday(birthday);
}else if("houseHold".equals(key)){
crmCustBas.setHouseHold(map.get(key));
}else if("degreeEducation".equals(key)){
crmCustBas.setDegreeEducation(map.get(key));
}else if("graduateSchool".equals(key)){
crmCustBas.setGraduateSchool(map.get(key));
}else if("politics".equals(key)){
crmCustBas.setPolitics(map.get(key));
}else if("mobilePhone".equals(key)){
crmCustBas.setMobilePhone(map.get(key));
}else if("phone".equals(key)){
crmCustBas.setPhone(map.get(key));
}else if("email".equals(key)){
crmCustBas.setEmail(map.get(key));
}else if("zip".equals(key)){
crmCustBas.setZip(map.get(key));
}else if("chuanZhen".equals(key)){
crmCustBas.setChuanZhen(map.get(key));
}else if("enjoy".equals(key)){
crmCustBas.setEnjoy(map.get(key));
}else if("position".equals(key)){
crmCustBas.setPosition(map.get(key));
}else if("joinOrgnise".equals(key)){
crmCustBas.setJoinOrgnise(map.get(key));
}else if("workExperience".equals(key)){
crmCustBas.setWorkExperience(map.get(key));
}
}
if(!"".equals(crmCustBas.getMobilePhone())&&crmCustBas.getMobilePhone()!=null){
QueryCondition queryCondition = new QueryCondition();
queryCondition.setQueryObject(CrmCustBas.class);
queryCondition.addField(new QueryField("mobilePhone",crmCustBas.getMobilePhone(),QueryField.CONDITION_EQ));
queryCondition.addField(new QueryField("custName",crmCustBas.getCustName(),QueryField.CONDITION_EQ));
List<CrmCustBas> haveList = basDao.query(queryCondition);
if(haveList.size()>0){
continue;
}else{
crmCustBas.setCustNo(getNo());
crmCustBas.setCustPoint(0);
basDao.save(crmCustBas);
}
}
}
}
return flag;
}
UtilExcel:
public static List resolveExcel(String arrayCloumns,InputStream inputStream,int sheetCount,Object object,int startRows) throws BasException{
List list=new ArrayList();
Workbook book =null;
try {
//解析模板爲,號分割串
book = Workbook.getWorkbook(inputStream);
Sheet sheet = book.getSheet(sheetCount);
//列數
int columnCount=sheet.getColumns();
//行數
int rowCount=sheet.getRows();
Cell cell = null;
String[] arraycol=arrayCloumns.split(",");
for (int i = startRows; i <rowCount; i++) {
Object obj=UtilBean.getNewClass(object.getClass());
for (int j = 0; j <columnCount; j++) {
String arrcol=arraycol[j];
cell =sheet.getCell(j, i);
String val=cell.getContents();
//若是是日期類型
if(cell.getType() == CellType.DATE){
DateCell datec11 = (DateCell)cell;
Date date = datec11.getDate();
val = UtilDate.formatDate(date);
}
//若是是金額類型
if(val.contains("$")){
val = val.replace("$", "").replace(",", "");
}
if(object instanceof Map){
((Map)obj).put(arrcol,val);
}
else{
BeanUtils.setProperty(obj, arrcol, val);
}
}
list.add(obj);
}
}catch (Exception e) {
log.error("excel解析錯誤,錯誤消息:"+e.getMessage());
throw new BasRuntimeException("excel解析錯誤",e);
}finally{
if(book!=null){
book.close();
}
}
return list;
}
以上一二是我在CRM用的方式,接下來是我在活動平臺項目所用的方式,其實也差很少,可是爲了讓本身能夠記住,仍是將其寫下來了。
3、導入excel
<form id="formUpload" name="formUpload" action="<%=request.getContextPath()%>/import_linkman_excel.do" method="post" enctype="multipart/form-data">
<table class="tableCon2" style="background:#fff;">
<tbody><tr>
<td><div class="importUserLayer">
<table>
<tbody><tr>
<td width="154" height="57" align="right" valign="top">選擇須要導入的文件:</td>
<td width="434"><p>
<input type="file" id="myfiles" style="border: 1px solid #CCCCCC; height: 24px;background: #FFFFFF" name="myfiles" size="45">
</p>
<p>支持<font style="color:#FF0000">.XLS</font>格式 </p></td>
</tr>
<tr>
<td height="40" align="right">導入到組:</td>
<td>
<select name="groupId" id="group" class="textfield citySelect" style="width:82px;height:22px; text-indent:0px;">
</select></td>
</tr>
<tr>
<td colspan="2"><div class="Contactsindex">
<p><strong> 提示:導入文件需知足三個條件:</strong></p>
<p style=" padding-left:20px;"> a) 文件第一行必須爲每列數據的名稱,例如:姓名、手機、郵件地址、職位、部門等。</p>
<p style=" padding-left:20px;"> b) 導入信息必須包含姓名、手機或mail。</p>
<p style=" padding-left:20px;"> c) 文件爲.csv或.xls格式。目前不支持Excel2007或更高版本的xlsx文件,請另存爲Excel2003格式或者.csv格式。</p>
</div></td>
</tr>
</tbody></table>
</div></td>
</tr>
</tbody></table>
</form>
function saveFile(){
$("#formUpload").submit();
}
action:
@RequestMapping(value = "import_linkman_excel.do")
public String importExcel(@RequestParam(value = "groupId",required = false)String groupId,@RequestParam MultipartFile[] myfiles,HttpServletRequest request,HttpServletResponse response){
MultipartFile imgFileName = myfiles[0];
String booleanString = "";
String fileName = imgFileName.getOriginalFilename();
if(fileName!=null||!"".equals(fileName)){
String ext = fileName.substring(fileName.lastIndexOf(".")+1,fileName.length());
//對擴展名進行小寫轉換
ext = ext.toLowerCase();
if("xls".equals(ext)){
try {
List<CommLinkmanInfoVO> list = UtilExcel.resolveExcel("linkmanName,sex,email,phone,mobilePhone,fax,zipCode,company,deptName,industryTypeNo,position,address,qq",imgFileName.getInputStream(),0,new CommLinkmanInfoVO(),1);
if(list.size()>0){
for(CommLinkmanInfoVO commLinkmanInfoVO : list){
List<CommLinkmanInfoVO> haveList = commLinkmanInfoServiceImpl.queryListByGroupId(groupId);
if(haveList.size()>0){
for(CommLinkmanInfoVO equalVO : haveList){
if(equalVO.getPhone()==commLinkmanInfoVO.getPhone()){
//預留已經存在的返回消息
continue;
}else {
commLinkmanInfoVO.setGroupId(groupId);
commLinkmanInfoServiceImpl.saveLinkman(commLinkmanInfoVO);
}
}
}else{
commLinkmanInfoVO.setGroupId(groupId);
commLinkmanInfoServiceImpl.saveLinkman(commLinkmanInfoVO);
}
}
}
} catch (Exception e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
return "redirect:/comm_linkman_index.do?groupId="+groupId;
}
四 導出excel
@RequestMapping(value = "export_select_link.do")
public String exportSelect(@RequestParam(value="delistJson",required = false)String delistJson,@RequestParam(value="groupId",required = false)String groupId,
@RequestParam(value="groupName",required = false)String groupName,HttpServletResponse response,HttpServletRequest request
){
List<IdVO> idVOs = JsonUtils.getList(delistJson,IdVO.class);
List<CommLinkmanInfoVO> list = new ArrayList<CommLinkmanInfoVO>();
if(idVOs.size()>0){
List<String> eventListId = new ArrayList<String>();
for(int i=0;i< idVOs.size();i++){
String id = idVOs.get(i).getId();
eventListId.add(id);
}
list = commLinkmanInfoServiceImpl.queryListByListId(eventListId);
try {
groupName = new String(groupName.getBytes("iso-8859-1"),"utf-8");
if(groupName==null||"".equals(groupName)){
groupName = "所選聯繫人";
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
String uploadPath = "/upload";
String realUploadFilePath = request.getSession().getServletContext().getRealPath(uploadPath);
String filePath = realUploadFilePath+ File.separator+groupName + "名單.xls";
try {
UtilExcel.writeListToExcel(groupName + "名單", list, filePath, "linkmanName,sex,email,phone,mobilePhone,fax,zipCode,company,deptName,industryTypeNo,position,address,qq;", "名字,性別,郵箱,電話,手機,傳真,郵編,公司,部門,行業,職位,地址,QQ");
String filename = groupName+"名單"+".xls";
filename = new String(filename.getBytes("utf-8"),"iso-8859-1");
response.reset();
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition", "p_w_upload;filename="+filename);
OutputStream ouputStream = response.getOutputStream();
InputStream inputStream = new FileInputStream(new File(filePath));
byte buffer[]=new byte[4*1024];
int len = 0;
while((len = inputStream.read(buffer)) != -1)//
{
ouputStream.write(buffer,0,len);
}
ouputStream.flush();
ouputStream.close();
UtilFile.delFile(filePath);
} catch (Exception e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
return null;
}
public static void writeListToExcel(String titleName,List list, String filename, String sheetName, String columnNames,
String columnDisplayNames, boolean isDeleteFile, String sumOnColumn, String promptStringForSum,String conditions){
//入參校驗
if (list == null || UtilString.isEmpty(filename) || UtilString.isEmpty(columnNames)
|| UtilString.isEmpty(columnDisplayNames)){
throw new BasRuntimeException("參數錯誤,請保證參數爲非空。");
}
String[] columnName = columnNames.split(",");
String[] columnDisplayName = columnDisplayNames.split(",");
Workbook rwBook=null;
WritableWorkbook book = null;
if(UtilString.isEmpty(sheetName)){
sheetName = "sheet1";
}
int numberOfFields = columnName.length, result = 0;
int[] columnWidths = new int[numberOfFields];
try {
String path =filename.substring(0,filename.lastIndexOf("\\"));
if(path!=null&&!"".equals(path)){
File tmp = new File(path);
if(!tmp.isDirectory()){
tmp.mkdirs();
}
}
File file = new File(filename);
if(isDeleteFile && file.exists())
file.delete();
//建立一個可寫的工做簿
if(file.exists()) {
rwBook = Workbook.getWorkbook(file);
book = Workbook.createWorkbook(file, rwBook);
} else{
book = Workbook.createWorkbook(file);
}
int workingSheetNo = file.exists() ? book.getNumberOfSheets() + 1 : 1;
//添加一個工做表
WritableSheet ws = book.createSheet(sheetName, workingSheetNo);
//輸出大標題
ws.mergeCells(0, 0, numberOfFields-1, 0);
ws.setRowView(0, 500);
Label labelC00 = new Label(0, 0, titleName, getBigTitleStyle(16));
ws.addCell(labelC00);
//添加帶有字型Formatting的對象,用來輸出標題行
int k = 1,row=2;
if(!UtilString.isEmpty(conditions)){
k=2;
row=3;
ws.mergeCells(0, 1, numberOfFields-1, 1);
ws.setRowView(0, 500);
Label labelC01 = new Label(0, 1, conditions, getBigTitleStyle(16));
ws.addCell(labelC01);
}
//輸出列頭
for (int j = 0; j < numberOfFields; j++) {
//設置列寬度
jxl.write.Label label = new jxl.write.Label(j, k, columnDisplayName[j], getColumnHeadStyle());
ws.addCell(label);
columnWidths[j] = columnDisplayName[j].length();
}
//建立數字單元格式對象
jxl.write.NumberFormat nf = new jxl.write.NumberFormat(DECIMAL_FORMAT);
jxl.write.WritableCellFormat wcfNumber = new jxl.write.WritableCellFormat(nf);
//建立TimeStamp單元格式對象
jxl.write.DateFormat dfTS = new jxl.write.DateFormat(DATE_FORMAT+ " hh:mm:ss");
jxl.write.WritableCellFormat wcfTimestamp = new jxl.write.WritableCellFormat(dfTS);
//建立日期單元格式對象
jxl.write.DateFormat dfDate = new jxl.write.DateFormat(DATE_FORMAT);
jxl.write.WritableCellFormat wcfDate = new jxl.write.WritableCellFormat(dfDate);
int indexForSumColumn = 0;
double total = 0;
boolean isNeededSum = !UtilString.isEmpty(sumOnColumn);
//將List中的對象輸出到excel
for (int i = 0; i < list.size(); i++) {
//Map map = (HashMap) list.get(i);//List中的每一個對象都是hashMap,map包含字段名和值
Object _object = list.get(i);
if (_object == null)
continue;
Map map=null;
Object vo = null;
if(_object instanceof Map){//判斷該List對象是Map仍是VO
map = (HashMap) list.get(i);
}else{
vo = list.get(i);
}
for (int column = 0; column < numberOfFields; column++) {
//當對象爲空時,若是繼續調用jxl的API,常常會出異常,因此先檢測
Object obj = null;
if(map!=null){
obj= map.get(columnName[column]);
} else if(vo!=null){
obj = UtilBean.getProperty(vo, columnName[column]);
}
if (obj == null)
continue;
//若是須要統計,將從map中讀到的值累加到total,同時設置統計列的位置,用於最後輸出統計信息
if (isNeededSum) {
if (columnName[column].equals(sumOnColumn)) {
total += Double.parseDouble(obj.toString());
indexForSumColumn = column;
}
}
//設置列的寬度值
if(obj.toString().length() > columnWidths[column])
columnWidths[column] = obj.toString().length();
if (obj instanceof String) {
jxl.write.Label label = new jxl.write.Label(column, row, (String) obj);
ws.addCell(label);
} else if ((obj instanceof Integer)) {
jxl.write.Number number = new jxl.write.Number(column, row, ((Integer) obj).doubleValue(), wcfNumber);
ws.addCell(number);
} else if (obj instanceof Timestamp) {
jxl.write.DateTime datetime = new jxl.write.DateTime(column, row, (Timestamp) obj, wcfTimestamp);
ws.addCell(datetime);
} else if (obj instanceof BigDecimal) {
jxl.write.Number number = new jxl.write.Number(column, row, ((BigDecimal) obj).doubleValue(), wcfNumber);
ws.addCell(number);
} else if (obj instanceof Double) {
jxl.write.Number number = new jxl.write.Number(column, row, ((Double) obj).doubleValue(), wcfNumber);
ws.addCell(number);
} else if (obj instanceof Float) {
jxl.write.Number number = new jxl.write.Number(column, row, ((Float) obj).doubleValue(), wcfNumber);
ws.addCell(number);
} else if ((obj instanceof Long)) {
jxl.write.Number number = new jxl.write.Number(column, row, ((Long) obj).doubleValue(), wcfNumber);
ws.addCell(number);
} else if ((obj instanceof Short)) {
jxl.write.Number number = new jxl.write.Number(column, row, ((Short) obj).doubleValue(), wcfNumber);
ws.addCell(number);
} else if (obj instanceof Date) {
jxl.write.DateTime datetime = new jxl.write.DateTime(column, row, (Date) obj, wcfDate);
ws.addCell(datetime);
} else if (obj instanceof Boolean) {
jxl.write.Boolean labelB = new jxl.write.Boolean (column, row, ((Boolean)obj).booleanValue());
ws.addCell(labelB);
} else {
//把其餘類型都做爲字符串處理
jxl.write.Label label = new jxl.write.Label(column, row, (String) obj);
ws.addCell(label);
}
}
row++;
}
//輸出統計信息
if (isNeededSum) {
jxl.write.Label labelPrompt = new jxl.write.Label(indexForSumColumn - 1, row + 1, promptStringForSum);
ws.addCell(labelPrompt);
jxl.write.Number number = new jxl.write.Number(indexForSumColumn, row + 1, total, wcfNumber);
ws.addCell(number);
//更新彙總信息的列寬度
if(promptStringForSum.length() > columnWidths[indexForSumColumn - 1])
columnWidths[indexForSumColumn - 1] = promptStringForSum.length();
if(String.valueOf(total).length() > columnWidths[indexForSumColumn])
columnWidths[indexForSumColumn] = String.valueOf(total).length();
}
//調整列的寬度
for (int i = 0; i < columnWidths.length; i++) {
//設定列的最大最小寬度爲200和6
if(columnWidths[i] > 100)
columnWidths[i] = 100;
if(columnWidths[i] < 6){
columnWidths[i] = 6;
}
ws.setColumnView(i, columnWidths[i]+1);
}
} catch (Exception e) {
log.error("寫Excel失敗。" + e.getMessage());
throw new BasRuntimeException("寫入Excel失敗",e);
} finally {
try {
if (book != null) {
book.write();
book.close();
if(rwBook!=null){
rwBook.close();
}
}
} catch (Exception e) {
}
}
}