简体   繁体   中英

Open an excel file using COM and save it as .xml file

Im trying the following code:

<?php

    $workbook = "D:\b2\\test.XLS";
    $sheet = "Sheet1";

    #Instantiate the spreadsheet component.
        $ex = new COM("Excel.sheet") or Die ("Did not connect");

    #Get the application name and version    
        print "Application name:{$ex->Application->value}<BR>" ; 
        print "Loaded version: {$ex->Application->version}<BR>"; 

    #Open the workbook that we want to use.
        $wkb = $ex->application->Workbooks->Open($workbook) or Die ("Did not open");

    #Create a copy of the workbook, so the original workbook will be preserved.
        $ex->Application->ActiveWorkbook->SaveAs("D:\b2\Ourtest.xml");  
        #$ex->Application->Visible = 1; #Uncomment to make Excel visible.



    #Optionally, save the modified workbook
        $ex->Application->ActiveWorkbook->SaveAs("D:\Ourtest.xml");                      
    #Close all workbooks without questioning
        $ex->application->ActiveWorkbook->Close("False");    
        unset ($ex);

    ?> 

This actually works and creates the Ourtest.xml file. But im getting characters like:

ÐÏࡱá > þÿ þÿÿÿ
I have tried with SaveAs("D:\\Ourtest.pdf") and it says the file has been corrupted or incorrectly decoded. Can anyone help me please?Thanks

That is because you are saving it as Excel Format. Check the Excel documentation for how to save it as an XML document - it might be a separate paramter to SaveAs or a different method alltogether ( Export* ).

EDIT: It seems SaveAs is the right method to use. Check the msdn documentation here . You probably want to specify the second parameter FileFormat . Maybe setting it to the XlFileFormat.xlXMLSpreadsheet value?

Problem solved by using

$ex->Application->ActiveWorkbook->SaveAs("D:\Ourtest.xml",46); 

46 is the value for xlXMLSpreadsheet
Thanks everyone

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM