HTML到Excel:数据格式更改

时间:2014-09-02 16:41:59

标签: javascript export-to-excel

我有以下代码将HTML表格导出到Excel:

function exportToExcel(tableID)
{
    var detailsTable= document.getElementById(tableID);
    var oExcel = new ActiveXObject("Excel.Application");
    var oBook = oExcel.Workbooks.Add;
    var oSheet = oBook.Worksheets(1);
    for (var y=0;y<detailsTable.rows.length;y++)
    {
        for (var x=0;x<detailsTable.rows(y).cells.length;x++)
        {
            oSheet.Cells(y+1,x+1)= detailsTable.rows(y).cells(x).innerText;
        }
    }

    oExcel.Visible = true;
    oExcel.UserControl = true;
    oExcel.Columns.AutoFit();
    oExcel.Rows.Autofit();
}

导出有效但Excel在某些情况下会更改日期。而不是DD / MM / YYYY,它改为MM / DD / YYYY。

  

例如:在HTML中日期为29/05/2014(DD / MM / YYYY),在Excel中日期为29/05/2014(DD / MM / YYYY)。在HTML中,日期是2014年7月2日(DD / MM / YYYY),日期是2014年2月7日(MM / DD / YYYY),最后一种情况是错误的。

试图将javascript日期格式化为:

var now = new Date();
now.format("dd/mm/yyyy");

试图在没有幸运的情况下使用NumberFormat:

oExcel.Cells(y+1,x+1).NumberFormat = "DD/MM/YYYY"; 

试图在没有幸运的情况下使用TD中的风格:

style="mso-number-format:"dd\/mm\/yyyy"

更新

添加(作为测试):

oSheet.Cells(y+1,x+1).NumberFormat = "[$-F800]dddd, mmmm dd, yyyy"

在第二个for内,实际上格式化日期。我可以看到日期在这一点上已经错了。我的意思是,在表格中显示07/11/2014(年/月/日)并且在出口中显示11/07/2014(mm / dd / yyyy)

3 个答案:

答案 0 :(得分:1)

Check this solution using XLSX library. 除日期格式外,它还会四舍五入数字。此解决方案解决了这两个问题。

HTML:

<div class="container">
<table class="table " #table1>
<thead>
<tr>
<th>Name
<th>Dob(DD/MM/YYYY)
<th>Id
<th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of colors;index as i">
<td [style.color]="colors[i]">
{{item.name}}
</td>
<td t='s' [style.color]="colors[i]">//This t='s' solves the issue.
{{item.dob}}
</td>
<td t='s' [style.color]="colors[i]">
<!-- This is most important t='s' -->
{{item.id}}
</td>

</tr>
</tbody>
</table>
<button type="button" (click)="importTable2()">Export Table Two</button>
</div>

TS代码:

import {
  Component,
  ViewChild,
  ElementRef
} from '@angular/core';
import * as XLSX from 'xlsx';

import {
  Observable
} from 'rxjs/Observable';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  @ViewChild('table') table: ElementRef;
  @ViewChild('table1') table1: ElementRef;


  colors = [{
      name: 'Rubecaa',
      dob: '11/10/1998',
      id: '1000100020202010101AB'
    },
    {
      name: 'Zena',
      dob: '17/11/1998',
      id: '10001000202020101010'
    } //Id is string but sometimes it may contains only  number.
  ];



  importTable2() {
    const ws: XLSX.WorkSheet = XLSX.utils.table_to_sheet(this.table1.nativeElement);
    const wb: XLSX.WorkBook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

    /* save to file */
    XLSX.writeFile(wb, 'Table2.xlsx');

  }
}

答案 1 :(得分:0)

这是我用来将html表转换为csv和excel的不同方法。它是一个独立的平台,即当ActiveXObject不可用时也可以工作。所以代码如下,希望它可以帮到你。

您的表格代码应具有以下结构:

         <table>
            <thead>
                <tr class="list">
                    <th>Column Header</th>
                    <th>Column Header</th>
                    <th>Column Header</th>
                </tr> 
            </thead>
            <tbody>

                    <tr class="list">
                        <td>11</td>
                        <td style="background: #33cc00;">11</td>
                        <td>22</td>
                    </tr>

                    <tr class="list odd">
                        <td>22</td>
                        <td style="background: #33cc00;">22</td>
                        <td>22</td>
                    </tr>



            </tbody>
        </table>  

请注意,只需将类名作为列表分配给excel文件中所需的行。

然后jquery部分

        $u("#btnXLS").click(function(){

            var xls = jQuery(".list").map(function(a,i){
                return $u.trim($u(this).text()).split(/\s*\n\s*/).join("\t");
            }).toArray().join("\r\n");
            download(xls, "All_Data.xls", "application/vnd.ms-excel");

        });

下载功能如下

        function download(strData, strFileName, strMimeType) 
        {
            var D = document,
            a = D.createElement("a");
            var Data="Date :-"+Date();
            Data +="\n\n"+strData;
            strData =Data;
            strFileName=strFileName.substr(0,strFileName.indexOf('.'));
            strFileName +=Date();
            if(strMimeType.indexOf("text/csv") >= 0)
                strFileName +=".csv";
            else
                strFileName +=".xls";
            strMimeType= strMimeType || "application/octet-stream";
            if (window.MSBlobBuilder) { //IE10+ routine
                var bb = new MSBlobBuilder();
                bb.append(strData);
                return navigator.msSaveBlob(bb, strFileName);
            } /* end if(window.MSBlobBuilder) */
            if ('download' in a) { //html5 A[download]
                if(!window.URL){
                    a.href= window.URL.createObjectURL(new Blob([strData]));

            }else{
                    a.href = "data:" + strMimeType + "," + encodeURIComponent(strData);
            }

                a.setAttribute("download", strFileName);
                a.innerHTML = "downloading...";
                D.body.appendChild(a);
                setTimeout(function() {
                    a.click();
                    D.body.removeChild(a);
                }, 66);
                return true;
            } /* end if('download' in a) */
            //do iframe dataURL download (old ch+FF):
            var f = D.createElement("iframe");
            D.body.appendChild(f);
            f.src = "data:" +  strMimeType   + "," + encodeURIComponent(strData);

            setTimeout(function() {
                D.body.removeChild(f);
            }, 333);
            return true;
        } /* end download() */

答案 2 :(得分:0)

这可能不是您想要的,但我有一个Web应用程序,它在格式良好的表中显示数据,如果他们想要在excel中,我只是将完全相同的数据写入新页面,但更改标题mime type excel,效果很好!获取格式,颜色等。很好地显示标题。只是一个想法。