Search code examples
angularjscpu-word

Copying table(s) from MS Word to Web Form


I have a project coming up where I need to have a way to copy a table from MS word and paste it into a form. I know the contents of the table (IE, Columns), but some of the data is malformed (IE, it has a TAB in the text value of a cell). I need to parse this out cleanly.

As an example, I have a table with revision history data (Date, Who Made the Change, Version Number update, and description of changes). Once parsed, I would ideally like a JSON structure

myTable = [
{date:"2023-01-01",approver:"John Smith",version:"1.0.1",description:"I made some important changes"},
{date:"2023-01-01",approver:"Bob Smith",version:"1.0.2",description:"Undid John's Changes"}
]
  

I am working in Angular/JS and can get most of it to parse, but wondered if there was a clean library or something to help with this.

Thanks


Solution

  • I was able to solve this myself. The data pastes with \n for rows and \t for columns. the extra lines in some of the data caused the initial process to fail, but I ended up looping through, finding the lines without \t in them and adding them to the previous array element.

    $('#paste-block').on('change',function(){
            $scope.revHistory.data = [];
     
            let d = $('#paste-block').val();
            d = d.split('\n');
            let tA = [];
            for (var e of d){
                if (e.search('\t') !== -1){
                    tA.push(e);
                } else {
                    tA[tA.length -1] = tA[tA.length -1] + '\n' + e;
                }
            }
            for (var i in tA){
                let e = tA[i].split('\t');
                let o = {
                    date:e[0],
                    initials:e[1],
                    revision:e[2],
                    comments:e[3],
                }
                $scope.revHistory.data.push(o);
            }
            console.log($scope.revHistory.data);