天天看點

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" target="_blank" rel="external nofollow" >

<link rel="stylesheet" type="text/css" href="/css/icon.css" target="_blank" rel="external nofollow" >

<link rel="stylesheet" type="text/css" href="/css/font.css" target="_blank" rel="external nofollow" >

</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;">

</td>

</tr>

<tr>

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

(Excel格式請嚴格按照模闆填寫,否則容易上傳失敗。)

</td>

</tr>

<tr>

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

</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;">

</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;

public class BaseController {

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

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();

}

}

}

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();

}

}

}

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();

}

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);

}

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();

}

}

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;

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);

}

}

@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);

}

@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());

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;

}

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;

}

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

String[] columnKeys) {

return DatasetUtilities

.createCategoryDataset(rowKeys, columnKeys, data);

}

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;

}

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;

}

public static void isFilePathExist(String fileAbsoluteName) throws IOException {

File file = new File(fileAbsoluteName);

if (!file.exists()) {

file.createNewFile();

}

}

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;

}

    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;  

    } 

    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;  

    }  

    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