IE 下 返回 json 上传下载 问题


springMVC项目配置的时候,返回结果:application/json,charset=utf-8 

这个是暂时不考虑修改了,(其他就是这个BUG。因为其他地方用到,以免引起其他BUG,影响现有的项目运行。)


下面直奔主题: 

分 3部分 :  JSP  + JS  + 后台代码

(1)上传页面 jsp

<%@ page language="java" pageEncoding="UTF-8"%>

<!DOCTYPE HTML>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

<meta http-equiv="Cache-Control"

content="no-cache, no-store, must-revalidate" />

<title>导入产品信息界面</title>

<script src="${pageContext.request.contextPath}/js/jquery.min.js"></script>

<!-- easyui -->

<script type="text/javascript" src="/js/jquery.easyui.min.js"></script>

<script type="text/javascript" src="/js/easyui-lang-zh_CN.js"></script>

<link rel="stylesheet" type="text/css" href="/css/easyui.css">

<link rel="stylesheet" type="text/css" href="/css/icon.css">

<link rel="stylesheet" type="text/css" href="/css/font.css">


</head>


<body>

<!-- 产品资料导入 -->

<form method="post" id="supplier_importDeliverUI_form" enctype="multipart/form-data"

style="height:100%;background-color: #E5E5E5;font-size: 14px;">

<table style="margin-left: 20px;">

<tbody>

<tr>

<td colspan="2" style="text-align: center;">

&nbsp;

</td>

</tr>

<tr>

<td colspan="2" style="text-align: center;">

(Excel格式请严格按照模板填写,否则容易上传失败。)

</td>

</tr>

<tr>

<td colspan="2" style="text-align: center;">

&nbsp;

</td>

</tr>

<tr>

<td style="text-align: right;">选择文件: </td>

<td>

<input id="filebox" class="easyui-filebox easyui-validatebox"name="deliversExcel"

style="width:220px" data-options="required:true,buttonText:'选择文件'">  

</td>

</tr>

<tr>

<td colspan="2" style="text-align: center;">

&nbsp;

</td>

</tr>

<tr>

<td colspan="2" style="text-align: center;">

<button style="width:122px" 

type="submit" data-options="iconCls:'icon-right'">导入产品信息</button>

</td>

</tr>

</tbody>

</table>

</form>

<script type="text/javascript" src="/js/importDeliverUI.js"></script>

</body>

</html>

        

(2) importDeliverUI.js  

$(function() {

$('#supplier_importDeliverUI_form').form({

url : '/importDeliversInfos.do',

onSubmit : function() {

var val = $('#filebox').textbox('getValue');

if (val) {

// 调用父窗口的滚动条

window.parent.openProgressBar();

return true;

} else {

window.parent.alertMsg('信息提示', '请选择文件', 'warning');

return false;

}

},

success : function(json) {

// 收到返回消息之后先隐藏滚动条

//window.parent.closeProgressBar();

var json = eval("(" + json + ")");

// 判断是否成功,成功则关闭窗口,刷新界面并提示消息,失败则跳警告信息

if (json.reflag == true) {

window.parent.showMsg("成功提示", json.infoMsg);

} else {

window.parent.alertMsg("提示消息", json.infoMsg, 'error');

}

}

});

});

(3) 后台代码    UploadController  (重要的部分,我标记出来。1 接收文件,2 返回结果处理)

@RequestMapping("/productManage")

@Controller

public class UploadController  extends BaseController{


@RequestMapping("/importDeliversInfos")

public void importDeliversInfos(HttpServletRequest request,

@RequestParam("deliversExcel") CommonsMultipartFile receiveFile,HttpServletResponse response){

JsonMsgVo msg = new JsonMsgVo();

logger.info("importDeliversInfos");

try {

//  1 接收文件

String newFileName = super.receiveUploadFile(request, receiveFile);

if(newFileName.equals("isNotFile")){

//如果保存文件有问题

msg.setReflag(false);

msg.setInfoMsg("上传Excel格式有问题,或者文件已损坏,请重新尝试!");

}else{

//读取,解析Excel,获取二位数组

List<List<Object>> rows = ExcelUtils.readExcel(newFileName);

// 调用方法封装成vo对象

List<DeliverVO> vos = boDeliverService.parseListToVOs(rows);

// 当前登陆用户,做为(创建者,用户表主键)

UserVO userSession = (UserVO) request.getSession().getAttribute("loginUser");

BoUser user = boUserService.getBoUserByUserId(userSession.getBoUserId()); 

BoOrg boOrg = boOrgService.getTopOrgByOrgMark(userSession.getOrgMark());

user.setOrgMark(boOrg.getOrgMark());

// vo对象插入数据库

if(vos!=null&&vos.size()>0){

for (DeliverVO deliverVO : vos) {

// 根据vo插入主表数据

BoDeliver boDeliver = boDeliverService.saveDeliverInfo(deliverVO, user);

BoDeliverDetailedService.saveBoDeliverDetailed(deliverVO,boDeliver);

}

}

msg.setReflag(true);

msg.setInfoMsg("上传产品信息成功!");

}

} catch (Exception e) {

logger.error("供应商产品管理中心,SupplierManageController控制器,importCustomerInfos方法异常:"

+ e.getMessage());

msg.setReflag(false);

msg.setInfoMsg("上传Excel中断,数据格式有误,或者导入的某些信息已在数据库中存在!");

}

                2 返回结果处理

                //自己写的方法,打回response输出流

try {

super.renderJSON(msg, response, "text/html;charset=utf-8");

} catch (IOException e) {

logger.error("供应商产品管理中心,SupplierManageController控制器,importCustomerInfos方法异常:" + e.getMessage());

}

}

}

//    BaseController  这个方法比较大,里面内容较多

package com.panasign.controller;


import java.awt.Color;

import java.awt.Font;

import java.awt.Graphics;

import java.awt.image.BufferedImage;

import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import java.io.OutputStream;

import java.io.PrintWriter;

import java.util.Random;

import java.util.UUID;


import javax.imageio.ImageIO;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.springframework.web.multipart.commons.CommonsMultipartFile;


import com.alibaba.fastjson.JSON;

import com.panasign.common.util.ExcelUtils;


/**

 * 父类controller,所有子类controller都规定必须继承它,抽离一些大家都要用到的方法。

 * 

 * @copyright:柏年软件

 * @project:柏年云项目第一期

 */

public class BaseController {

private static final String CONTENT_TYPE = "image/jpeg";


/**

* 把一个object对象以json格式打回客户端,默认格式为application/json

* @param object

* @param response

* @throws IOException

*/

public void renderJSON(Object object, HttpServletResponse response)

throws IOException {

String json = "";

PrintWriter pw = null;

try {

json = JSON.toJSONStringWithDateFormat(object,

"yyyy-MM-dd HH:mm:ss");

response.setContentType("application/json;charset=UTF-8");

pw = response.getWriter();

pw.write(json);

pw.flush();

} catch (IOException e) {

throw e;

} finally {

if (pw != null) {

pw.close();

}

}

}


/**

*  把一个object对象以json格式打回客户端,contentType格式自己传入

* @param object

* @param response

* @param format

* @throws IOException

*/

public void renderJSON(Object object, HttpServletResponse response, String format)

throws IOException {

String json = "";

PrintWriter pw = null;

try {

json = JSON.toJSONStringWithDateFormat(object,

"yyyy-MM-dd HH:mm:ss");

response.setContentType(format);

pw = response.getWriter();

pw.write(json);

pw.flush();

} catch (IOException e) {

throw e;

} finally {

if (pw != null) {

pw.close();

}

}

}

/**

* 生成验证码图片

* @param request

* @param response

* @throws IOException

*/

public void renderImageCode(HttpServletRequest request,

HttpServletResponse response) throws IOException {

response.setHeader("Pragma", "No-cache");

response.setHeader("Cache-Control", "no-cache");

response.setContentType(CONTENT_TYPE);

response.setDateHeader("Expires", 0);

int width = 65, height = 40;

BufferedImage image = new BufferedImage(width, height,

BufferedImage.TYPE_INT_RGB);

OutputStream os = response.getOutputStream();

Graphics g = image.getGraphics();

Random random = new Random();

g.setColor(getRandColor(200, 250));

g.fillRect(0, 0, width, height);

g.setFont(new Font("Arial", Font.PLAIN, 28));

g.setColor(getRandColor(160, 200));

for (int i = 0; i < 155; i++) {

int x = random.nextInt(width);

int y = random.nextInt(height);

int xl = random.nextInt(12);

int yl = random.nextInt(12);

g.drawLine(x, y, x + xl, y + yl);

}

String sRand = "";

for (int j = 0; j < 4; j++) {

String rand = String.valueOf(random.nextInt(10));

sRand += rand;

g.setColor(new Color(20 + random.nextInt(110), 20 + random

.nextInt(110), 20 + random.nextInt(110)));

//后面的30是字体底边的高度

g.drawString(rand, 13 * j + 6, 30);

}

//验证码内容放入session

request.getSession().setAttribute("checkImage", sRand);

g.dispose();

ImageIO.write(image, "JPEG", os);

os.flush();

os.close();

os = null;

response.flushBuffer();

}


/**

* renderImageCode()生成验证码图片专用,用来生成随机颜色

* @param fc

* @param bc

* @return

*/

private Color getRandColor(int fc, int bc) {

Random random = new Random();

if (fc > 255)

fc = 255;

if (bc > 255)

bc = 255;

int r = fc + random.nextInt(bc - fc);

int g = fc + random.nextInt(bc - fc);

int b = fc + random.nextInt(bc - fc);

return new Color(r, g, b);

}


/**

* 下载模板用的公共方法,路径固定为项目下面的Templates文件夹

* @param fileName

*            Templates文件夹下存在的的文件名,比如importCustomers.xls

* @param request

* @param response

* @throws Exception

*/

public void downloadTemplate(String fileName, HttpServletRequest request,

HttpServletResponse response) throws Exception {

request.setCharacterEncoding("UTF-8");

java.io.BufferedInputStream bis = null;

java.io.BufferedOutputStream bos = null;


String ctxPath = request.getSession().getServletContext()

.getRealPath("/")

+ "/" + "Templates/";


String downLoadPath = ctxPath + fileName;

try {

// 获取文件长度

long fileLength = new File(downLoadPath).length();

response.setCharacterEncoding("UTF-8");


// 1.设置文件ContentType类型,这样设置,会自动判断下载文件类型

response.setContentType("multipart/form-data");

// 2.设置文件头:最后一个参数是设置下载文件名

response.setHeader("Content-Disposition", "attachment;fileName="

+ fileName);

// 3、告诉浏览器,文件有多长

response.setHeader("Content-Length", String.valueOf(fileLength));


bis = new BufferedInputStream(new FileInputStream(downLoadPath));

bos = new BufferedOutputStream(response.getOutputStream());

byte[] buff = new byte[2048];

int bytesRead;

while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {

bos.write(buff, 0, bytesRead);

}

} catch (Exception e) {

e.printStackTrace();

} finally {

if (bis != null)

bis.close();

if (bos != null)

bos.close();

}

}


/**

* 接收上传的文件,保存后,返回保存后的绝对路径名

* @param request

* @param receiveFile

* @return 保存后的绝对路径名

* @throws Exception

*/

public String receiveUploadFile(HttpServletRequest request,

CommonsMultipartFile receiveFile) throws Exception {

String fileAbsolutePath = "isNotFile";

if (!receiveFile.isEmpty()) {

String path = request.getSession().getServletContext()

.getRealPath("/uploadFiles/"); // 获取本地存储路径

// logger.info(path);

String fileName = receiveFile.getOriginalFilename();

String fileType = fileName.substring(fileName.lastIndexOf("."));

// logger.info(fileType);

// 新建一个文件

String fileAbsoluteName = path + "/" + UUID.randomUUID().toString()

+ fileType;

ExcelUtils.isFilePathExist(fileAbsoluteName);

File file = new File(fileAbsoluteName);

// logger.info(file.getAbsolutePath());

// 将上传的文件写入新建的文件中

receiveFile.getFileItem().write(file);

fileAbsolutePath = file.getAbsolutePath();

}

return fileAbsolutePath;

}

}



// 不想贴太多代码的,但是没贴出来 重要的内容会不好,所以。

/**

 * 

 */

package com.panasign.common.util;


import java.awt.Color;

import java.awt.Font;

import java.awt.image.BufferedImage;

import java.io.ByteArrayOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.OutputStream;

import java.text.DecimalFormat;

import java.text.SimpleDateFormat;

import java.util.ArrayList;

import java.util.Iterator;

import java.util.LinkedList;

import java.util.List;

import javax.imageio.ImageIO;

import org.apache.poi.hssf.usermodel.HSSFCell;

import org.apache.poi.hssf.usermodel.HSSFClientAnchor;

import org.apache.poi.hssf.usermodel.HSSFPatriarch;

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.poifs.filesystem.POIFSFileSystem;

import org.apache.poi.ss.usermodel.Row;

import org.jboss.logging.Logger;

import org.jfree.chart.ChartFactory;

import org.jfree.chart.ChartUtilities;

import org.jfree.chart.JFreeChart;

import org.jfree.chart.StandardChartTheme;

import org.jfree.chart.axis.CategoryAxis;

import org.jfree.chart.axis.CategoryLabelPositions;

import org.jfree.chart.axis.NumberAxis;

import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;

import org.jfree.chart.plot.CategoryPlot;

import org.jfree.chart.plot.PlotOrientation;

import org.jfree.chart.renderer.category.LineAndShapeRenderer;

import org.jfree.chart.title.LegendTitle;

import org.jfree.chart.title.TextTitle;

import org.jfree.data.category.CategoryDataset;

import org.jfree.data.general.DatasetUtilities;

import org.apache.poi.hssf.usermodel.HSSFDateUtil;  

import org.apache.poi.xssf.usermodel.XSSFCell;  

import org.apache.poi.xssf.usermodel.XSSFRow;

import org.apache.poi.xssf.usermodel.XSSFSheet;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**

 * Excel 操作类,兼容2003跟2007

 * @copyright:柏年软件

 * @project:柏年云项目第一期

 */

public class ExcelUtils {

private static Logger logger = Logger.getLogger(ExcelUtils.class);

public static final String CHART_PATH = "E:/Excel/";

public static final String PHONECOUNT = "lineAndShap.jpg";

private static FileOutputStream fileOut = null;

private static BufferedImage bufferImg = null;

public static void main(String[] args) throws Exception {

List<String> printList = parseExcel(new File("F:\\普通用户信息Excel模板.xls"), 1);

for (String str : printList) {

logger.info(str);

}

}

/**

* 已经过时,请用readExcel()方法

* @param excel

* @return

* @throws IOException

*/

@Deprecated

private static HSSFWorkbook openWorkbookInstance(File excel) throws IOException {

FileInputStream in = null;

POIFSFileSystem fs = null;

try {

in = new FileInputStream(excel);

fs = new POIFSFileSystem(in);

} catch (Exception e) {

e.printStackTrace();

} finally {

in.close();

}

return new HSSFWorkbook(fs);

}


/**

* 已经过时,请用readExcel()方法

* @param excelFile

* @param startIndex

* @return

* @throws Exception

*/

@Deprecated

public static List<String> parseExcel(File excelFile, int startIndex) throws Exception {


List<String> excelList = new ArrayList<String>();


HSSFWorkbook workbook = openWorkbookInstance(excelFile);


HSSFSheet sheet = null; // HSSFSheet工作簿对象


for (int i = 0, sheetNum = workbook.getNumberOfSheets(); i < sheetNum; i++) {

sheet = workbook.getSheetAt(i);

// HSSFSheet sheet = openWBInstance(filePath).getSheetAt(0);//

// HSSFSheet工作簿对象// HSSFSheet


Iterator<Row> iterator = sheet.rowIterator();// 行迭代器,迭代对象是HSSFRow行对象


// logger.info(sheet.getLeftCol());

/**

* sheet.getLastRowNum() 最后一行的index,index从getFirstRowNum():0开始

* sheet.getPhysicalNumberOfRows() 实际编辑过的 行数,即使后来被删,但任然算构造了 的行

*/

HSSFRow row = null;// 工作簿中HSSFRow行对象


HSSFCell cell = null;// 工作簿中每行中的HSSFCell单元格对象


int currentRow = 0;// sheet中行的Index


int sumCell = -1;


while (iterator.hasNext()) {

String rowRecord = "";// 封装每行记录的拼接字符串


row = (HSSFRow) iterator.next();


currentRow = row.getRowNum();// 获取行Index,以0开始


if (startIndex != -1 && currentRow == 0) {// 一般工作簿第一行是列字段名称,通常不读取

sumCell = row.getLastCellNum();// 获取当前行表格的列数

continue;

}

sumCell = (sumCell == -1 ? row.getLastCellNum() : sumCell);


// 一般工作簿第一行是列字段名称,通常不读取

for (int k = 0; k < sumCell; k++) {

String cellData = "";// 封装单元格数据

cell = row.getCell(k);// 获取单元格对象

if (cell != null) {

//int currentCell = cell.getColumnIndex();//一行中单元格的Index位置,获取列Index,以0开始

/*

* 取值前先判断单元格内数据类型,再根据不同方法取值

*/

switch (cell.getCellType()) {

    case HSSFCell.CELL_TYPE_STRING:

    cellData = cell.getStringCellValue().trim();

    break;

    case HSSFCell.CELL_TYPE_NUMERIC:

    //cellData = DateUtils.getFormatDate(cell.getDateCellValue(), "yyyyMMdd");

    cellData = String.valueOf((int)cell.getNumericCellValue());

    break;

                            case HSSFCell.CELL_TYPE_BLANK:

                                cellData = "";

                                break;

    default:

    break;

}

   //String cellData = cell.toString().trim();

rowRecord += cellData + ",";

} else {

rowRecord += ",";

}

}

excelList.add(rowRecord + "%");// 将Excel中的每行记录用逗号拼接成字符串并以%结尾封装到List中

}

}


return excelList;

}


/**

* 生成折线图,只针对2003版本,不支持2007

* @param data

* @param rowKeys

* @param columnKeys

*/

public static String makeLineAndShapeChart(String chartTitle,

double[][] data, String[] rowKeys, String[] columnKeys) {

CategoryDataset dataset = getBarData(data, rowKeys, columnKeys);

String picName = createTimeXYChar(chartTitle, "", "", dataset,

PHONECOUNT);

return picName;

}


/**

* 柱状图,折线图 数据集,只针对2003版本,不支持2007

* @param data

* @param rowKeys

* @param columnKeys

* @return

*/

public static CategoryDataset getBarData(double[][] data, String[] rowKeys,

String[] columnKeys) {

return DatasetUtilities

.createCategoryDataset(rowKeys, columnKeys, data);


}


/**

* 生成折线图,返回图片名字,只针对2003版本,不支持2007

* @param chartTitle

* @param x

* @param y

* @param xyDataset

* @param charName

* @return

*/

public static String createTimeXYChar(String chartTitle, String x,

String y, CategoryDataset xyDataset, String charName) {


JFreeChart chart = ChartFactory.createLineChart(chartTitle, x, y,

xyDataset, PlotOrientation.VERTICAL, true, true, false);


chart.setTextAntiAlias(false);

chart.setBackgroundPaint(Color.WHITE);

// 设置图标题的字体重新设置title

Font font = new Font("隶书", Font.BOLD, 25);

TextTitle title = new TextTitle(chartTitle);

title.setFont(font);

chart.setTitle(title);

LegendTitle legend = chart.getLegend();

if (legend != null) {

legend.setItemFont(new Font("宋体", Font.BOLD, 20));

}

// 设置面板字体

Font labelFont = new Font("宋体", Font.TRUETYPE_FONT, 12);

// 创建主题样式

StandardChartTheme standardChartTheme = new StandardChartTheme("CN");

// 设置标题字体

standardChartTheme.setExtraLargeFont(new Font("隶书", Font.BOLD, 20));

// 设置图例的字体

standardChartTheme.setRegularFont(new Font("宋书", Font.PLAIN, 15));

// 设置轴向的字体

standardChartTheme.setLargeFont(new Font("宋书", Font.PLAIN, 15));

// 应用主题样式

ChartFactory.setChartTheme(standardChartTheme);

chart.setBackgroundPaint(Color.WHITE);


CategoryPlot categoryplot = (CategoryPlot) chart.getPlot();

// x轴 // 分类轴网格是否可见

categoryplot.setDomainGridlinesVisible(true);

// y轴 //数据轴网格是否可见

categoryplot.setRangeGridlinesVisible(true);


categoryplot.setRangeGridlinePaint(Color.WHITE);// 虚线色彩


categoryplot.setDomainGridlinePaint(Color.WHITE);// 虚线色彩


categoryplot.setBackgroundPaint(Color.lightGray);


// 设置轴和面板之间的距离

// categoryplot.setAxisOffset(new RectangleInsets(5D, 5D, 5D, 5D));


CategoryAxis domainAxis = categoryplot.getDomainAxis();


domainAxis.setLabelFont(labelFont);// 轴标题

domainAxis.setTickLabelFont(labelFont);// 轴数值


domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45); // 横轴上的

// Lable

// 45度倾斜

// 设置距离图片左端距离

domainAxis.setLowerMargin(0.0);

// 设置距离图片右端距离

domainAxis.setUpperMargin(0.0);


NumberAxis numberaxis = (NumberAxis) categoryplot.getRangeAxis();

numberaxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

numberaxis.setAutoRangeIncludesZero(true);


// 获得renderer 注意这里是下嗍造型到lineandshaperenderer!!

LineAndShapeRenderer lineandshaperenderer = (LineAndShapeRenderer) categoryplot

.getRenderer();


lineandshaperenderer.setBaseShapesVisible(true); // series 点(即数据点)可见

lineandshaperenderer.setBaseLinesVisible(true); // series 点(即数据点)间有连线可见


// 显示折点数据

lineandshaperenderer

.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());

lineandshaperenderer.setBaseItemLabelsVisible(true);


FileOutputStream fos_jpg = null;

String chartName = null;

try {

isFilePathExist(CHART_PATH);

chartName = CHART_PATH + charName;

fos_jpg = new FileOutputStream(chartName);

// 将报表保存为png文件

ChartUtilities.writeChartAsPNG(fos_jpg, chart, 500, 510);

// return chartName;

} catch (Exception e) {

e.printStackTrace();

return null;

} finally {

try {

fos_jpg.close();

logger.info("create time-createTimeXYChar.");

} catch (Exception e) {

e.printStackTrace();

}

}

// 下载折线图

// OutputStream os = new FileOutputStream("CHART_PATH+PHONECOUNT");

OutputStream os;

try {

os = new FileOutputStream(chartName);

// 由ChartUtilities生成文件到一个体outputStream中去

try {

ChartUtilities.writeChartAsJPEG(os, chart, 1000, 800);

} catch (IOException e) {

e.printStackTrace();

}

} catch (FileNotFoundException e1) {

e1.printStackTrace();

}

return chartName;

}

/**

* 我只是个加注释的,我也不知道这个方法什么用,只知道它只针对2003版本,不支持2007,请自行研究

* @param sheetName

* @param chartName

* @param fromFile

* @param i

* @param toPath

* @return

* @throws FileNotFoundException

* @throws IOException

*/

public static Boolean toExcel(String sheetName, String chartName,

File fromFile, Integer[] i, String toPath)

throws FileNotFoundException, IOException {

POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(fromFile));

HSSFWorkbook wb = new HSSFWorkbook(fs);

HSSFSheet sheet = wb.getSheet(sheetName);

// 处理图片文件,以便产生ByteArray

ByteArrayOutputStream handlePicture = new ByteArrayOutputStream();

handlePicture = handlePicture(chartName);

HSSFPatriarch patriarch = sheet.createDrawingPatriarch();

HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 100, 50,

(short) 3, 3, (short) 15, 29);

patriarch.createPicture(anchor, wb.addPicture(

handlePicture.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));

for (int j = 0; j < i.length; j++) {

HSSFRow row = sheet.getRow(j + 1);

row.getCell(1).setCellValue(i[j]);

}

HSSFRow row = sheet.getRow(32);

row.getCell(1).setCellFormula("SUM(B2:B32)");

try {

fileOut = new FileOutputStream(toPath);

isFilePathExist(toPath);

wb.write(fileOut);

} catch (Exception e) {

e.printStackTrace();

return false;

} finally {

if (fileOut != null) {

try {

fileOut.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

return true;

}


/**

* 判断文件是否存在,不存在则创建

* @param fileAbsoluteName 文件绝对路径名

* @throws IOException

*/

public static void isFilePathExist(String fileAbsoluteName) throws IOException {

File file = new File(fileAbsoluteName);

if (!file.exists()) {

file.createNewFile();

}

}


/**

* 我只是个加注释的,我也不知道这个方法用来干嘛的,不过看样子像是个读图片的方法,返回字节数组输出流,请自行研究

* @param pathOfPicture

* @return

* @throws IOException 

*/

private static ByteArrayOutputStream handlePicture(String pathOfPicture) throws IOException {

ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();

bufferImg = ImageIO.read(new File(pathOfPicture));

ImageIO.write(bufferImg, "jpeg", byteArrayOut);

return byteArrayOut;

}


/**

 * 读取2003格式的Excel文件,封装成二维数组格式

 * @param file

 * @return

 * @throws IOException

 */

    private static List<List<Object>> read2003Excel(File file)  

            throws IOException {  

        List<List<Object>> list = new LinkedList<List<Object>>();  

        HSSFWorkbook hwb = new HSSFWorkbook(new FileInputStream(file));  

        HSSFSheet sheet = hwb.getSheetAt(0);  

        Object value = null;  

        HSSFRow row = null;  

        HSSFCell cell = null;  

        logger.info("读取office 2003 excel内容如下:");  

        for (int i = sheet.getFirstRowNum(); i <= sheet  

                .getPhysicalNumberOfRows(); i++) {  

            row = sheet.getRow(i);  

            if (row == null) {  

                continue;  

            }  

            List<Object> linked = new LinkedList<Object>();  

            for (int j = row.getFirstCellNum(); j <= row.getLastCellNum(); j++) {  

                cell = row.getCell(j);  

                if (cell == null) {  

                    continue;  

                }  

                DecimalFormat df = new DecimalFormat("0");// 格式化 number String  

                // 字符  

                SimpleDateFormat sdf = new SimpleDateFormat(  

                        "yyyy-MM-dd HH:mm:ss");// 格式化日期字符串  

                DecimalFormat nf = new DecimalFormat("0.00");// 格式化数字  

                switch (cell.getCellType()) {  

                case XSSFCell.CELL_TYPE_STRING:  

                    // logger.info(i + "行" + j + " 列 is String type");  

                    value = cell.getStringCellValue();  

                    System.out.print("  " + value + "  ");  

                    break;  

                case XSSFCell.CELL_TYPE_NUMERIC:  

                    // logger.info(i + "行" + j  

                    // + " 列 is Number type ; DateFormt:"  

                    // + cell.getCellStyle().getDataFormatString());  

                    if ("@".equals(cell.getCellStyle().getDataFormatString())) {  

                        value = df.format(cell.getNumericCellValue());  

  

                    } else if ("General".equals(cell.getCellStyle()  

                            .getDataFormatString())) {  

                        value = nf.format(cell.getNumericCellValue());  

                    } else {  

                        value = sdf.format(HSSFDateUtil.getJavaDate(cell  

                                .getNumericCellValue()));  

                    }  

                    System.out.print("  " + value + "  ");  

                    break;  

                case XSSFCell.CELL_TYPE_BOOLEAN:  

                    // logger.info(i + "行" + j + " 列 is Boolean type");  

                    value = cell.getBooleanCellValue();  

                    System.out.print("  " + value + "  ");  

                    break;  

                case XSSFCell.CELL_TYPE_BLANK:  

                    // logger.info(i + "行" + j + " 列 is Blank type");  

                    value = "";  

                    System.out.print("  " + value + "  ");  

                    break;  

                default:  

                    // logger.info(i + "行" + j + " 列 is default type");  

                    value = cell.toString();  

                    System.out.print("  " + value + "  ");  

                }  

                if (value == null || "".equals(value)) {  

                    continue;  

                }  

                linked.add(value);  

  

            }  

            logger.info("");  

            list.add(linked);  

        }  

        return list;  

    } 

    /**

     * 读取2007格式的excel文件,封装成二维数组格式

     * @param file

     * @return

     * @throws IOException

     */

    private static List<List<Object>> read2007Excel(File file)  

            throws IOException {  

  

        List<List<Object>> list = new LinkedList<List<Object>>();  

        // String path = System.getProperty("user.dir") +  

        // System.getProperty("file.separator")+"dd.xlsx";  

        // logger.info("路径:"+path);  

        // 构造 XSSFWorkbook 对象,strPath 传入文件路径  

        XSSFWorkbook xwb = new XSSFWorkbook(new FileInputStream(file));  

  

        // 读取第一章表格内容  

        XSSFSheet sheet = xwb.getSheetAt(0);  

        Object value = null;  

        XSSFRow row = null;  

        XSSFCell cell = null;  

        logger.info("读取office 2007 excel内容如下:");  

        //循环每一行

        for (int i = sheet.getFirstRowNum(); i <= sheet  

                .getPhysicalNumberOfRows(); i++) {  

            row = sheet.getRow(i);  

            if (row == null) {  

                continue;  

            }  

            List<Object> linked = new LinkedList<Object>();  

            for (int j = row.getFirstCellNum(); j <= row.getLastCellNum(); j++) {  

                cell = row.getCell(j);  

                if (cell == null) {  

                    continue;  

                }  

                DecimalFormat df = new DecimalFormat("0");// 格式化 number String  

                // 字符  

                SimpleDateFormat sdf = new SimpleDateFormat(  

                        "yyyy-MM-dd HH:mm:ss");// 格式化日期字符串  

                DecimalFormat nf = new DecimalFormat("0.00");// 格式化数字  

  

                switch (cell.getCellType()) {  

                case XSSFCell.CELL_TYPE_STRING:  

                    // logger.info(i + "行" + j + " 列 is String type");  

                    value = cell.getStringCellValue();  

                    System.out.print("  " + value + "  ");  

                    break;  

                case XSSFCell.CELL_TYPE_NUMERIC:  

                    // logger.info(i + "行" + j  

                    // + " 列 is Number type ; DateFormt:"  

                    // + cell.getCellStyle().getDataFormatString());  

                    if ("@".equals(cell.getCellStyle().getDataFormatString())) {  

                        value = df.format(cell.getNumericCellValue());  

  

                    } else if ("General".equals(cell.getCellStyle()  

                            .getDataFormatString())) {  

                        value = nf.format(cell.getNumericCellValue());  

                    } else {  

                        value = sdf.format(HSSFDateUtil.getJavaDate(cell  

                                .getNumericCellValue()));  

                    }  

                    System.out.print("  " + value + "  ");  

                    break;  

                case XSSFCell.CELL_TYPE_BOOLEAN:  

                    // logger.info(i + "行" + j + " 列 is Boolean type");  

                    value = cell.getBooleanCellValue();  

                    System.out.print("  " + value + "  ");  

                    break;  

                case XSSFCell.CELL_TYPE_BLANK:  

                    // logger.info(i + "行" + j + " 列 is Blank type");  

                    value = "";  

                    // logger.info(value);  

                    break;  

                default:  

                    // logger.info(i + "行" + j + " 列 is default type");  

                    value = cell.toString();  

                    System.out.print("  " + value + "  ");  

                }  

                if (value == null || "".equals(value)) {  

                    continue;  

                }  

                linked.add(value);  

            }  

            logger.info("");  

            list.add(linked);  

        }  

        return list;  

    }  

    

    /**

     * 传入Excel绝对路径文件名,自动判断是2003还是2007类型,解析后返回对象二位数组

     * @param fileAbsoluteName

     * @return List<List<Object>>

     * @throws IOException

     */

    public static List<List<Object>> readExcel(String fileAbsoluteName) throws IOException{

    List<List<Object>> list=new LinkedList<List<Object>>();

    isFilePathExist(fileAbsoluteName);

    if(fileAbsoluteName.substring(fileAbsoluteName.lastIndexOf(".")).equals(".xls")){

    //2003处理

    list = read2003Excel(new File(fileAbsoluteName));

    }else{

    //2007处理

    list = read2007Excel(new File(fileAbsoluteName));

    }

    return list;

    }

}

-------------------------------越贴越多。其实问题解决。就在

super.renderJSON(msg, response, "text/html;charset=utf-8");


重要事情说3遍:封装自己的返回结果。虽然有未知的BUG




转载于:https://my.oschina.net/tangxi/blog/502021

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值