簡體   English   中英

HTML 到 Excel:數據格式更改

[英]HTML to Excel: Data format changes

我有以下代碼可以將 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 中,日期是 02/07/2014 (DD/MM/YYYY) 在 Excel 中,日期是 07/02/2014 (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 (dd/mm/yyyy),在導出中顯示 11/07/2014 (mm/dd/yyyy)

使用 XLSX 庫檢查此解決方案。 此外,除了日期格式之外,它還對數字進行了四舍五入。 此解決方案修復了這兩個問題。

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>

代碼:

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

  }
}

這是我用來將 HTML 表轉換為 CSV 和 excel 的不同方法。它獨立於平台,即在 ActiveXObject 不可用時也能工作。

您的表代碼應具有以下結構。 請注意,它只是將類名作為列表分配給您想要在 Excel 文件中的行。

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

});

// download() function
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() */
<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>

這可能不是您想要的,但我有一個 Web 應用程序,可以在格式良好的表格中顯示數據,如果他們想要在 excel 中顯示數據,我只需將完全相同的數據寫入新頁面,但將標題更改為 mime 類型excel 並且效果很好! 獲取格式、顏色等。很好地顯示標題。 只是一個想法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM