Search code examples
javascriptexcelactivexobject

How to format generated Excel file when using new ActiveXObject("Excel.Application");


I am exporting data from a HTML table to excel using new ActiveXObject("Excel.Application")...But the problem is I am not able to determine the column width, row width and few other formatting options...Can anybody please help...??? I am using below code to generate the Excel file..

var ExcelApp = new ActiveXObject("Excel.Application");
var ExcelSheet = new ActiveXObject("Excel.Sheet");
ExcelSheet.Application.Visible = true;

for(var i=1; i<rowCount+1; i++) 
{   
    for(var j=0; j<colCount; j++) 
    {           
        str = mytable.getElementsByTagName("tr")[i].getElementsByTagName("td")[j].innerHTML;
        ExcelSheet.ActiveSheet.Cells(i+1,j+1).Value = str;
    }
}

Solution

  • Try this

    This will give the Column Width and Row Height.

    Col = ExcelSheet.ActiveSheet.Columns("A").ColumnWidth;
    rowHeight = ExcelSheet.ActiveSheet.Rows(1).RowHeight;
    

    Few other formatting options

    ExcelSheet.ActiveSheet.PageSetup.Orientation = 2;
    ExcelSheet.ActiveSheet.PageSetup.PaperSize = 5;
    ExcelSheet.ActiveSheet.Columns("A").WrapText = true;
    ExcelSheet.ActiveSheet.Range("A1:B10").NumberFormat = "0";
    ExcelSheet.ActiveSheet.Range("A1:B10").HorizontalAlignment = -4131;
    ExcelSheet.ActiveSheet.Cells(i+1,j+1).Interior.ColorIndex="15";
    ExcelSheet.ActiveSheet.Name="Blah Blah";
    

    If you have Excel then I would recommend recording a macro for the rest of the formatting options and then simply amending that code in js.