使用spreadjs作为核心控件使用教程(2)

1:spreadjs数据存储方案。

(1):以json形式保存。(2):直接保存excel文件

其中方法二已经在官方有个Java的实现方案就不再重复了。

2:以json形式保存的解决方案。

这里我选择为json形式保存是为了后期优化,如果后期性能有问题,可能还需要细化,比如json文件再以拆分为多个sheet,前端点击哪个sheet再加载哪个sheet的数据,修改成功也只需要保存到对应的sheet去,我的环境是excel文件会比较大,excel文件转成文本文件(json)的大小对比为1:8左右,也就是说10M的表格传到后台在传输中这个json字符串就快100M了,可以分分钟把你浏览器搞崩溃,所以必须得前后端进行压缩。

function importAndAdd(json) {
//这里json是spreadjs前端导入的json,我是在前端导入顺便写入到服务器上。
 //var excelIo = new GC.Spread.Excel.IO();
  //  excelIo.open(excelFile, function (json) {
  //  }
//pako  官网:https://github.com/nodeca/pako   导入dist包下的pako.js即可.
    json = pako.gzip(JSON.stringify(json), {to: "string"});
    $.ajax({
        url:'/xxxxx/xxxxx',
        type:"post",
        dataType:"json",
        data:{
            workbookObj:json
        },
        success:function (data) {
        
        },
        error:function (resp) {
            alert(JSON.stringify(resp));
        }
    })
后台:
@RequestMapping(value = "importExcelInfo")
public ServerResponse importExcelInfo(HttpServletRequest request){
    //TODO 查询excel 信息的集合  tomcat需要设置东西
    String excelJson=request.getParameter("workbookObj");
    Integer userId=modelRequest.getUserId();
    Long millis=System.currentTimeMillis();


    StringBuffer path=new StringBuffer();
    path.append(CommonConstant.localBasePath);
    path.append(userId+"\\");
    path.append(millis+"\\");
    System.out.println("path:"+path);
    File filePath = new File(path.toString());
    if(!filePath.exists()){
        filePath.mkdirs();
    }
    try {
        excelJson=GZIPUtils.uncompress(excelJson);
    } catch (Exception e) {
        e.printStackTrace();
    }
    path.append(modelRequest.getExcelName()+".json");
    File file = new File(path.toString());
    if(!file.exists()){
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    try {
        if(excelJson!=null && !"null".equals(excelJson) ){
             FileUtils.writeFileContent(path.toString(),excelJson);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    DataSourceContextHolder.clearDBType();

    //插入和生成文件都要成功。
    if(sqlFlag){
        return    ServerResponse.createBySuccessMessage(modelRequest.getId());
    }else{
        return ServerResponse.createBySuccessError();
    }
}

 

GZIPUtils:

public class GZIPUtils {
    /**
     * GZIP压缩
     *
     */
    public static String compress(String str) throws IOException {
        if (null == str || str.length() <= 0) {
            return str;
        }
        // 创建一个新的输出流
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        // 使用默认缓冲区大小创建新的输出流
        GZIPOutputStream gzip = new GZIPOutputStream(out);
        // 将字节写入此输出流
        gzip.write(str.getBytes("utf-8"));  //因为后台默认字符集有可能是GBK字符集,所以此处需指定一个字符集
        gzip.close();
        // 使用指定的 charsetName,通过解码字节将缓冲区内容转换为字符串
        return out.toString("ISO-8859-1");
    }

    // 解压缩
    public static String uncompress(String str) throws IOException {
        if (str == null || str.length() == 0) {
            return str;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayInputStream in = new ByteArrayInputStream(str
                .getBytes("iso-8859-1"));
        GZIPInputStream gunzip = new GZIPInputStream(in);
        byte[] buffer = new byte[256];
        int n;
        while ((n = gunzip.read(buffer)) >= 0) {
            out.write(buffer, 0, n);
        }
        // toString()使用平台默认编码,也可以显式的指定如toString(&quot;GBK&quot;)
        return out.toString("utf-8");
    }

}
以上就是前端压缩到后台解压将真实的内容写入到服务器中去。下面是读取,读取需要服务端压缩,然后客户端也就是浏览器解压。

核心代码如下:

@RequestMapping(value = "xxxx", produces = "application/text; charset=utf-8")
public String show(HttpServletResponse response){
   
//filepath=BASE_LOCAL_URL+"1111\\1111\\1111.json";//注意filepath的内容;
    System.out.println("id:"+id+"filepath:"+filepath);
    File file=new File(filepath);
    StringBuffer b=new StringBuffer();
    BufferedReader brname;
    try {
        InputStreamReader read = new InputStreamReader(new FileInputStream(file), "UTF-8");
        BufferedReader bufferedReader = new BufferedReader(read);
        String sname = null;
        while ((sname = bufferedReader.readLine()) != null) {
            // System.out.println(sname);
            b.append(sname);
        }
    } catch (Exception e1) {
        // TODO Auto-generated catch block
        System.out.println("e1.getMessage():"+e1.getMessage());
        e1.printStackTrace();

    }
    String jsonText=b.toString();
    try {
        String gizpJsonText=GZIPUtils.compress(jsonText);
        System.out.println("压缩前:"+jsonText.length()+"压缩后长度:"+gizpJsonText.length());
        return gizpJsonText;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return jsonText;
}

 

这里面其实就差一个url,给url赋个值就可以用了。

 

前端解压:

 

$.ajax({
    type: 'post',
    url:"/xxx/xxx",
    async:true,
    data:{},
    dataType:"text",
    success:function(resp){
        if (resp.length>0){
            //不为空的excel=导入等方式。
           var json =pako.ungzip( resp, { to: 'string' } ); // ungzip
            var spread2 = $("#ss").data("workbook");
            spread2.fromJSON(JSON.parse(json));
 
    },
    error:function(error){}

});

通过对比解压前后可以发现效率有了大大的提升。下面部分将是在spreadjs加上自己的操作,比如右键额外加菜单等等。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值