Programing

웹 페이지에서 Excel로 표를 내보내려면 어떻게해야합니까?

lottogame 2020. 8. 25. 19:17
반응형

웹 페이지에서 Excel로 표를 내보내려면 어떻게해야합니까?


웹 페이지에서 Excel로 표를 내보내려면 어떻게해야합니까? 내보내기에 모든 서식과 색상이 포함되기를 원합니다.


멀리서 보면 테이블에서 Excel로 가장 깨끗하고 가장 쉽게 내보낼 수있는 것은 Jquery DataTables Table Tools 플러그인입니다. 데이터를 정렬, 필터링, 정렬 및 페이징하는 그리드가 제공되며 몇 줄의 추가 코드와 두 개의 작은 파일이 포함되어있어 Excel, PDF, CSV, 클립 보드 및 프린터로 내보낼 수 있습니다.

다음은 필요한 모든 코드입니다.

  $(document).ready( function () {
    $('#example').dataTable( {
        "sDom": 'T<"clear">lfrtip',
        "oTableTools": {
            "sSwfPath": "/swf/copy_cvs_xls_pdf.swf"
        }
    } );
} );

따라서 배포가 빠르고 브라우저 제한이 없으며 서버 측 언어가 필요하지 않으며 무엇보다도 이해하기 쉽습니다. 그것은 윈-윈입니다. 그러나 한 가지 제한 사항은 엄격한 열 형식 지정입니다.

서식과 색상이 절대적인 거래를 방해하는 경우, 제가 찾은 유일한 100 % 신뢰할 수있는 크로스 브라우저 방법은 서버 측 언어를 사용하여 코드에서 적절한 Excel 파일을 처리하는 것입니다. 내 솔루션은 PHPExcel 입니다. HTML 만 제공하면 모든 브라우저에서 Excel의 최신 버전으로 서식을 지정하여 내보내기를 적극적으로 처리하는 유일한 솔루션입니다 . 하지만 명확히하겠습니다. 첫 번째 솔루션만큼 쉽지는 않으며 리소스를 많이 사용하기도합니다. 그러나 플러스 측면에서는 PDF로 직접 출력 할 수도 있습니다. 그리고 일단 구성하면 매번 작동합니다.

업데이트 -2016 년 9 월 15 일 : TableTools는 " 버튼 " 이라는 새 플러그인을 사용하여 중단되었습니다. 이러한 도구는 이전 TableTools 확장과 동일한 기능을 수행하지만 설치가 훨씬 쉽고 최신 브라우저 용 HTML5 다운로드를 사용합니다. HTML5 표준을 지원하지 않는 브라우저를 위해 원래 Flash 다운로드로 대체 할 수있는 기능이 있습니다. 2011 년에이 응답을 게시 한 이후 많은 댓글에서 알 수 있듯이 TableTools의 주요 약점이 해결되었습니다. 개발자와 사용자 모두에게 단순히 대량의 데이터를 처리하기에 충분한 DataTables를 여전히 권장하지 않습니다.


오래 전에 Excel 콘텐츠 형식으로 보내면 Excel이 표가있는 HTML 파일을 열 수 있다는 것을 발견했습니다. 위의 문서를 고려하십시오.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>Java Friends</title>
</head>
<body>
  <table style="font-weight: bold">
    <tr style="background-color:red"><td>a</td><td>b</td></tr>
    <tr><td>1</td><td>2</td></tr>
  </table>    
</body>
</html>

다음 북마크릿을 실행했습니다.

javascript:window.open('data:application/vnd.ms-excel,'+document.documentElement.innerHTML);

사실 Excel 파일로 다운로드 할 수 있습니다. 그러나 예상 한 결과를 얻지 못했습니다. 파일이 OpenOffice.org Writer에서 열려있었습니다. 이것이 내 문제입니다.이 컴퓨터에는 Excel이 없어서 더 잘 시도 할 수 없습니다. 또한이 트릭은 6 년 전에 구형 브라우저와 MS Office의 골동품 버전에서 작동했기 때문에 오늘 작동할지 여부를 말할 수 없습니다.

어쨌든 위의 문서에서 이론상 전체 문서를 Excel 파일로 다운로드하는 버튼을 추가했습니다.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>Java Friends</title>
</head>
<body>
  <table style="font-weight: bold">
    <tr style="background-color:red"><td>a</td><td>b</td></tr>
    <tr><td>1</td><td>2</td></tr>
    <tr>
      <td colspan="2">
        <button onclick="window.open('data:application/vnd.ms-excel,'+document.documentElement.innerHTML);">
            Get as Excel spreadsheet
        </button>
      </td>
    </tr>
  </table>    
</body>
</html>

파일에 저장하고 버튼을 클릭하십시오. 나는 것 사랑 은 일을하거나하지 않을 경우 심지어는 작동하지 않았다 말하는에 대한 언급을 요청할 수 있도록, 알고.


이전 Excel 2003 XML 형식 (OpenXML 이전)을 사용하여 원하는 XML이 포함 된 문자열을 만든 다음 클라이언트 측에서 데이터 URI를 사용하여 XSL MIME 형식을 사용하여 파일을 열거 나 파일을 보낼 수 있습니다. 서버 측에서 Excel mimetype "Content-Type : application / vnd.ms-excel"을 사용하여 클라이언트에 전송합니다.

  1. Excel을 열고 원하는 서식과 색상으로 워크 시트를 만듭니다.
  2. Excel 통합 문서를 "XML Spreadsheet 2003 (*. xml)"로 저장합니다.
  3. 메모장과 같은 텍스트 편집기에서 결과 파일을 열고 값을 애플리케이션의 문자열에 복사합니다.
  4. 데이터 URI와 함께 클라이언트 측 접근 방식을 사용한다고 가정하면 코드는 다음과 같습니다.
    
    <script type="text/javascript">
    var worksheet_template = '<?xml version="1.0"?><ss:Workbook xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">'+
                 '<ss:Styles><ss:Style ss:ID="1"><ss:Font ss:Bold="1"/></ss:Style></ss:Styles><ss:Worksheet ss:Name="Sheet1">'+
                 '<ss:Table>{{ROWS}}</ss:Table></ss:Worksheet></ss:Workbook>';
    var row_template = '<ss:Row ss:StyleID="1"><ss:Cell><ss:Data ss:Type="String">{{name}}</ss:Data></ss:Cell></ss:Row>';
    </script>
    
    
  5. 그런 다음 문자열 바꾸기를 사용하여 워크 시트 템플릿에 삽입 할 행 모음을 만들 수 있습니다.
    
    <script type="text/javascript">
    var rows = document.getElementById("my-table").getElementsByTagName('tr'),
      row_data = '';
    for (var i = 0, length = rows.length; i < length; ++i) {
    row_data += row_template.replace('{{name}}', rows[i].getElementsByTagName('td')[0].innerHTML);
    }
    </script>
    
    
  6. 정보가 수집되면 최종 문자열을 만들고 데이터 URI를 사용하여 새 창을 엽니 다.

    
    <script type="text/javascript">
    var worksheet = worksheet_template.replace('{{ROWS}}', row_data);

    window.open('data:application/vnd.ms-excel,'+worksheet); </script>

이전 브라우저는 데이터 URI 체계를 지원하지 않으므로이를 지원하지 않는 브라우저에 대해 파일 서버 측을 생성해야 할 수도 있습니다.

데이터 URI 콘텐츠에 대해 base64 인코딩을 수행해야 할 수도 있습니다.이 경우 js 라이브러리 가 필요할 수 있으며 데이터 URI의 MIME 유형 뒤에 '; base64'문자열을 추가해야합니다.


Excel에는 추가 프로그래밍없이 거의 모든 웹 페이지에서 데이터를 검색 할 수있는 "웹 쿼리"라는 약간 알려진 기능이 있습니다.

웹 쿼리는 기본적으로 Excel 내에서 직접 HTTP 요청을 실행하고 수신 된 데이터의 일부 또는 전체를 워크 시트에 복사합니다.

웹 쿼리를 정의한 후에는 Excel을 종료하지 않고도 언제든지 새로 고칠 수 있습니다. 따라서 실제로 데이터를 "내보내고"파일에 저장할 필요가 없습니다. 데이터베이스 에서처럼 데이터를 새로 고치는 것이 좋습니다.

Excel에서 특정 필터 기준 등을 묻는 메시지를 표시하여 URL 매개 변수를 사용할 수도 있습니다.

그러나 지금까지 알아 차린 단점은 다음과 같습니다.

  • 자바 스크립트가 실행되지 않기 때문에 동적으로로드 된 데이터에 액세스 할 수 없습니다.
  • URL 길이가 제한됨

다음 은 Excel에서 웹 쿼리를 만드는 방법에 대한 질문입니다. 웹 페이지에서 외부 데이터를 가져 오는 방법에 대한 Microsoft 도움말 사이트로 연결됩니다.


이것은 PHP이지만 자바 스크립트로 변경할 수 있습니다.

<?php>
$colgroup = str_repeat("<col width=86>",5);
$data = "";
$time = date("M d, y g:ia");
$excel = "<html xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:x=\"urn:schemas-microsoft-com:office:excel\" xmlns=\"http://www.w3.org/TR/REC-html40\">
<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">
<html>
<head>
<meta http-equiv=\"Content-type\" content=\"text/html;charset=utf-8\" />
<style id=\"Classeur1_16681_Styles\">
.xl4566 {
color: red;
}
</style>
</head>
<body>
<div id=\"Classeur1_16681\" align=center x:publishsource=\"Excel\">
<table x:str border=0 cellpadding=0 cellspacing=0 style=\"border-collapse: collapse\">
<colgroup>$colgroup</colgroup>
<tr><td class=xl2216681><b>Col1</b></td><td class=xl2216681><b>Col2</b></td><td class=xl2216681 ><b>Col3</b></td><td class=xl2216681 ><b>Col4</b></td><td class=xl2216681 ><b>Col5</b></td></tr>
<tr><td class=xl4566>1</td><td>2</td><td>3</td><td>4</td><td>5</td></tr>
</table>
</div>
</body>
</html>";
  $fname = "Export".time().".xls";
  $file = fopen($fname,"w+");
  fwrite($file,$excel);
  fclose($file);
  header('Content-Type: application/vnd.ms-excel');
  header('Content-Disposition: attachment; filename="'.basename($fname).'"');
  readfile($fname);
  unlink($fname); ?>    

First, I would not recommend trying export Html and hope that the user's instance of Excel picks it up. My experience that this solution is fraught with problems including incompatibilities with Macintosh clients and throwing an error to the user that the file in question is not of the format specified. The most bullet-proof, user-friendly solution is a server-side one where you use a library to build an actual Excel file and send that back to the user. The next best solution and more universal solution would be to use the Open XML format. I've run into a few rare compatibility issues with older versions of Excel but on the whole this should give you a solution that will work on any version of Excel including Macs.

Open XML


mozilla still support base 64 URIs. This allows you to compose dynamically the binary content using javascript:

<a href="data:application/vnd.ms-excel<base64 encoded binary excel content here>"> download xls</a>

if your excel file is not very fancy (no diagrams, formulas, macroses) you can dig into the format and compose bytes for your file, then encode them with base64 and put in to the href

refer to https://developer.mozilla.org/en/data_URIs


This is actually more simple than you'd think: "Just" copy the HTML table (that is: The HTML code for the table) into the clipboard. Excel knows how to decode HTML tables; it'll even try to preserve the attributes.

The hard part is "copy the table into the clipboard" since there is no standard way to access the clipboard from JavaScript. See this blog post: Accessing the System Clipboard with JavaScript – A Holy Grail?

Now all you need is the table as HTML. I suggest jQuery and the html() method.


This code is IE only so it is only useful in situations where you know all of your users will be using IE (like, for example, in some corporate environments.)

<script Language="javascript">
function ExportHTMLTableToExcel()
{
   var thisTable = document.getElementById("tbl").innerHTML;
   window.clipboardData.setData("Text", thisTable);
   var objExcel = new ActiveXObject ("Excel.Application");
   objExcel.visible = true;

   var objWorkbook = objExcel.Workbooks.Add;
   var objWorksheet = objWorkbook.Worksheets(1);
   objWorksheet.Paste;
}
</script>

Assumptions:

  1. given url

  2. the conversion has to be done on client side

  3. systems are Windows, Mac and linux

Solution for Windows:

python code that open the ie window and has access to it: theurl variable contain the url ('http://')

ie = Dispatch("InternetExplorer.Application")
ie.Visible = 1
ie.Navigate(theurl)

Note: if the page is not accessible directly, but login, you will need to handle this by entering the form data and emulating the user actions with python

here is the example

from win32com.client import Dispatch
ie.Document.all('username').value=usr
ie.Document.all('password').value=psw

the same manner for retrieval of data from web page. Let's say element with id 'el1' contain the data. retrieve the element text to the variable

el1 = ie.Document.all('el1').value

then when data is in python variable, you can open the excel screen in similar manner using python:

from win32com.client import Dispatch
xlApp = Dispatch("Excel.Application")
xlWb = xlApp.Workbooks.Open("Read.xls")
xlSht = xlWb.WorkSheets(1)
xlSht.Cells(row, col).Value = el1

Solution for Mac:

only the tip: use AppleScript - it has simple and similar API as win32com.client Dispatch

Solution for Linux:

java.awt.Robot might work for this it has click, key press (hot keys can be used), but none API for Linux that I am aware about that can work as simple as AppleScript


simple google search turned up this:

If the data is actually an HTML page and has NOT been created by ASP, PHP, or some other scripting language, and you are using Internet Explorer 6, and you have Excel installed on your computer, simply right-click on the page and look through the menu. You should see "Export to Microsoft Excel." If all these conditions are true, click on the menu item and after a few prompts it will be imported to Excel.

if you can't do that, he gives an alternate "drag-and-drop" method:

http://www.mrkent.com/tools/converter/


And now there is a better way.

OpenXML SDK for JavaScript.

https://openxmlsdkjs.codeplex.com/


There are practical two ways to do this automaticly while only one solution can be used in all browsers. First of all you should use the open xml specification to build the excel sheet. There are free plugins from Microsoft available that make this format also available for older office versions. The open xml is standard since office 2007. The the two ways are obvious the serverside or the clientside.

The clientside implementation use a new standard of CSS that allow you to store data instead of just the URL to the data. This is a great approach coz you dont need any servercall, just the data and some javascript. The killing downside is that microsoft don't support all parts of it in the current IE (I don't know about IE9) releases. Microsoft restrict the data to be a image but we will need a document. In firefox it works quite fine. For me the IE was the killing point.

The other way is to user a serverside implementation. There should be a lot implementations of open XML for all languages. You just need to grap one. In most cases it will be the simplest way to modify a Viewmodel to result in a Document but for sure you can send all data from Clientside back to server and do the same.


   function normalexport() {

       try {
           var i;
           var j;
           var mycell;
           var tableID = "tblInnerHTML";
           var drop = document.getElementById('<%= ddl_sections.ClientID %>');
           var objXL = new ActiveXObject("Excel.Application");
           var objWB = objXL.Workbooks.Add();
           var objWS = objWB.ActiveSheet;
           var str = filterNum(drop.options[drop.selectedIndex].text);
           objWB.worksheets("Sheet1").activate; //activate dirst worksheet
           var XlSheet = objWB.activeSheet; //activate sheet
           XlSheet.Name = str; //rename


           for (i = 0; i < document.getElementById("ctl00_ContentPlaceHolder1_1").rows.length - 1; i++) {
               for (j = 0; j < document.getElementById("ctl00_ContentPlaceHolder1_1").rows(i).cells.length; j++) {
                   mycell = document.getElementById("ctl00_ContentPlaceHolder1_1").rows(i).cells(j);

                   objWS.Cells(i + 1, j + 1).Value = mycell.innerText;

                   //                                                objWS.Cells(i + 1, j + 1).style.backgroundColor = mycell.style.backgroundColor;
               }
           }

           objWS.Range("A1", "L1").Font.Bold = true;
           //                objWS.Range("A1", "L1").Font.ColorIndex = 2;
           //                 objWS.Range("A1", "Z1").Interior.ColorIndex = 47;

           objWS.Range("A1", "Z1").EntireColumn.AutoFit();

           //objWS.Range("C1", "C1").ColumnWidth = 50;

           objXL.Visible = true;

       } catch (err) {
           alert("Error. Scripting for ActiveX might be disabled")
           return
       }
       idTmr = window.setInterval("Cleanup();", 1);

   }


   function filterNum(str) {

       return str.replace(/[ / ]/g, '');
   }

참고URL : https://stackoverflow.com/questions/5524143/how-can-i-export-tables-to-excel-from-a-webpage

반응형