基于handsontable的web excel(上)

来源:互联网 发布:淘宝客服欢迎用语 编辑:程序博客网 时间:2024/06/06 15:00

handsontable是一个js插件,可以在网页上显示和操作excel。可以通过github或者handsontable的官方网站下载。首先上效果图:


使用handsontable显示excel步骤:

一、导入js和css:

    <link href="__STATIC__/handsontable/handsontable.full.css" rel="stylesheet" type="text/css">    <script type="text/javascript" src="__STATIC__/jquery-2.0.3.min.js"></script>    <script type="text/javascript" src="__STATIC__/handsontable/handsontable.full.js"></script>

二、创建一个div作为excel表格的容器:

    <div id="lina_main">    </div>
三、添加初始数据:

3.1、自定义行高和列宽,单位是px:

     var cell_width = [         100,120,90,100,100     ];     var cell_height = [         50,20,40,100     ];

3.2、设置单元格数据:

      var cell_data = [         ["", "Ford", "Tesla", "Toyota", "Honda"],         ["2017", 10, 11, 12, 13],         ["2018", 20, 11, 14, 13],         ["2019", 30, 15, 12, 13]      ];
3.3、调用Handsontable 绘制表格:

            var container = document.getElementById('lina_main');            hot = new Handsontable(container, {                data: cell_data, //导入数据                rowHeaders: true,                colHeaders: function(index) {                    return ++index;                },                autoColumnSize:false,                autoRowSize:false,//禁止行列自动计算距离                dropdownMenu: true,                manualRowResize: true,                manualColumnResize: true,//行列可拉缩                manualColumnMove: true,//可整行整列移动                manualRowMove: true,                mergeCells:true,//合并单元格                contextMenu: true,//使用菜单                colWidths: cell_width,//定义列宽度                rowHeights:cell_height ,//定义行高度                //水平:htLeft,htCenter,htRight,htJustify,                //垂直:htTop,htMiddle,htBottom。                //只读: readOnly htDimmed                cell:[ //设置单元格属性                    {row: 1, col: 1, readOnly: true,className: 'htCenter htMiddle'},                    {row: 2, col: 0, className: 'htCenter htMiddle'},                ],                mergeCells: [                    {row: 1, col: 1, rowspan: 2, colspan: 2}                ],//设置单元格合并情况                afterRowResize: function(currentRow, newSize) {                     cell_height[currentRow] =  newSize;                     hot.updateSettings({ rowHeights: cell_height });                 },//rowHeights为最小高度,为了设置比初始值更小的高度,编写此钩子            });


首先获取div容器,然后设置显示的参数,均有备注。需要注意以下参数:

1、在使用manualRowResize和manualColumnResize手动拉伸行列的时候,最好关闭autoRowSize和autoColumnSize。

2、cell参数可以单独设置某个单元格的格式,row和col表示单元格的行号列号(注意是从0开始),readOnly设置是否只读,className表示数据

在单元格中的显示是上下居中,左右居中等显示格式。

3、mergeCells参数表示合并单元格的情况,row和col表示单元格的行号和列号,rowspan和colspan表示跨域的行和列。

4、rowHeights设置了行初始化高度,同时也是最小高度(这个比较坑)。故在afterRowResize,行高改变之后重新赋值行的高度。

5、header表示头、true为默认的选项,即列号ABCD,如果想改为1、2、3或者其他,可以自定义函数。
至此,一个可编辑的excel便展示出来了。

原创粉丝点击