programing tip

Excel에서 웹 페이지로 복사 / 붙여 넣기

itbloger 2020. 10. 8. 07:45
반응형

Excel에서 웹 페이지로 복사 / 붙여 넣기


스프 레아 시트에서 웹 양식으로 복사하여 붙여 넣는 표준 방법이나 라이브러리가 있습니까? Excel에서 둘 이상의 셀을 선택하면 구분 기호가 사라지고 모두 웹 양식의 한 셀에 붙여 넣어집니다. VB에서해야합니까? 또는 웹 양식에서 붙여 넣기 작업이 시작되면 처리가 완료 될 수 있습니까?


구분 기호를 잃지 않고 셀은 탭 ( \t)으로 구분되고 \n은 양식에 표시되지 않을 수있는 줄 바꿈 ( ) 으로 구분됩니다 . 직접 시도해보십시오. Excel에서 메모장으로 콘텐츠를 복사하면 셀이 잘 정렬 된 것을 볼 수 있습니다. 그러면 탭으로 필드를 분할하고 다른 것으로 대체하는 것이 쉽습니다. 이렇게하면 필드에서 테이블도 만들 수 있습니다. 다음은 jQuery를 사용하는 예입니다.

var data = $('input[name=excel_data]').val();
var rows = data.split("\n");

var table = $('<table />');

for(var y in rows) {
    var cells = rows[y].split("\t");
    var row = $('<tr />');
    for(var x in cells) {
        row.append('<td>'+cells[x]+'</td>');
    }
    table.append(row);
}

// Insert into DOM
$('#excel_table').html(table);

따라서 본질적으로이 스크립트는 붙여 넣은 Excel 데이터에서 HTML 테이블을 만듭니다.


Tatu의 답변에 대한 응답으로 그의 솔루션을 보여주는 빠른 jsFiddle을 만들었습니다.

http://jsfiddle.net/duwood/sTX7y/

HTML

<p>Paste excel data here:</p>  
<textarea name="excel_data" style="width:250px;height:150px;"></textarea><br>
<input type="button" onclick="javascript:generateTable()" value="Genereate Table"/>
<br><br>
    <p>Table data will appear below</p>
<hr>
<div id="excel_table"></div>

JS

function generateTable() {
    var data = $('textarea[name=excel_data]').val();
    console.log(data);
    var rows = data.split("\n");

    var table = $('<table />');

    for(var y in rows) {
    var cells = rows[y].split("\t");
    var row = $('<tr />');
    for(var x in cells) {
        row.append('<td>'+cells[x]+'</td>');
    }
    table.append(row);
}

// Insert into DOM
$('#excel_table').html(table);
}

Tatu와 같은 아이디어 (우리 프로젝트에서 곧 필요합니다),하지만 정규 표현식을 사용합니다.
큰 데이터 세트의 경우 더 빠를 수 있습니다.

<html>
<head>
    <title>excelToTable</title>
    <script src="../libs/jquery.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
    <textarea>a1    a2  a3
b1  b2  b3</textarea>
    <div></div>
    <input type="button" onclick="convert()" value="convert"/>
    <script>
        function convert(){
            var xl = $('textarea').val();
            $('div').html( 
                '<table><tr><td>' + 
                xl.replace(/\n+$/i, '').replace(/\n/g, '</tr><tr><td>').replace(/\t/g, '</td><td>') + 
                '</tr></table>'
            )
        }
    </script>
</body>
</html>

OSX윈도우 , 다른 유형의 컨텐츠에 대한 클립 보드의 여러 종류가 있습니다. Excel에서 콘텐츠를 복사하면 데이터가 일반 텍스트와 html 클립 보드에 저장됩니다.

구분 기호 문제로 인해 문제가 발생하지 않는 올바른 방법은 HTML을 구문 분석하는 것입니다. http://jsbin.com/uwuvan/5 는 HTML 클립 보드를 얻는 방법을 보여주는 간단한 데모입니다. 핵심은 onpaste 이벤트에 바인딩하고

event.clipboardData.getData('text/html')

For any future googlers ending up here like me, I used @tatu Ulmanen's concept and just turned it into an array of objects. This simple function takes a string of pasted excel (or Google sheet) data (preferably from a textarea) and turns it into an array of objects. It uses the first row for column/property names.

function excelToObjects(stringData){
    var objects = [];
    //split into rows
    var rows = stringData.split('\n');

    //Make columns
    columns = rows[0].split('\t');

    //Note how we start at rowNr = 1, because 0 is the column row
    for (var rowNr = 1; rowNr < rows.length; rowNr++) {
        var o = {};
        var data = rows[rowNr].split('\t');

        //Loop through all the data
        for (var cellNr = 0; cellNr < data.length; cellNr++) {
            o[columns[cellNr]] = data[cellNr];
        }

        objects.push(o);
    }

    return objects;
}

Hopefully it helps someone in the future.


UPDATE: This is only true if you use ONLYOFFICE instead of MS Excel.

There is actually a flow in all answers provided here and also in the accepted one. The flow is that whenever you have an empty cell in excel and copy that, in the clipboard you have 2 tab chars next to each other, so after splitting you get one additional item in array, which then appears as an extra cell in that row and moves all other cells by one. So to avoid that you basically need to replace all double tab (tabs next to each other only) chars in a string with one tab char and only then split it.

An updated version of @userfuser's jsfiddle is here to fix that issue by filtering pasted data with removeExtraTabs

http://jsfiddle.net/sTX7y/794/

function removeExtraTabs(string) {
  return string.replace(new RegExp("\t\t", 'g'), "\t");
}

function generateTable() {
  var data = removeExtraTabs($('#pastein').val());
  var rows = data.split("\n");
  var table = $('<table />');

  for (var y in rows) {
    var cells = rows[y].split("\t");
    var row = $('<tr />');
    for (var x in cells) {
      row.append('<td>' + cells[x] + '</td>');
    }
    table.append(row);
  }

  // Insert into DOM
  $('#excel_table').html(table);
}

$(document).ready(function() {
  $('#pastein').on('paste', function(event) {
    $('#pastein').on('input', function() {
      generateTable();
      $('#pastein').off('input');
    })
  })
})

Excel 2007 has a feature for doing this under the "Data" tab that works pretty nicely.


Digging this up, in case anyone comes across it in the future. I used the above code as intended, but then ran into an issue displaying the table after it had been submitted to a database. It's much easier once you've stored the data to use PHP to replace the new lines and tabs in your query. You may perform the replace upon submission, $_POST[request] would be the name of your textarea:

$postrequest = trim($_POST[request]);
$dirty = array("\n", "\t");
$clean = array('</tr><tr><td>', '</td><td>');
$request = str_replace($dirty, $clean, $postrequest);

Now just insert $request into your database, and it will be stored as an HTML table.


Maybe it would be better if you would read your excel file from PHP, and then either save it to a DB or do some processing on it.

here an in-dept tutorial on how to read and write Excel data with PHP:
http://www.ibm.com/developerworks/opensource/library/os-phpexcel/index.html

참고URL : https://stackoverflow.com/questions/2006468/copy-paste-from-excel-to-a-web-page

반응형