in reply to Re: Modules for xlsx files
in thread Modules for xlsx files

Please read the questions carefully. I clearly mention that i need to open a template and write data into that. i dont need to open a new .xlsx file. With Spreadsheet::WriteExcelXML is it possible to open a existing file???

Replies are listed 'Best First'.
Re^3: Modules for xlsx files
by u65 (Chaplain) on Sep 28, 2015 at 12:20 UTC

    First, I see the author has made a new module Excel::Writer::XLSX to replace the deprecated Spreadsheet::WriteExcelXML.

    I would use separate reading and writing processes. First save the current file as a new, temp name. Read it to get data into suitable form. Write the new file updated as desired. Save the new, updated file. The clear separation should help maintenance of your code.

    I have used Excel readers and writers a lot but am not aware of any that can read and write the same stream, but then I have never needed an update capability either.

Re^3: Modules for xlsx files
by RonW (Parson) on Sep 28, 2015 at 21:23 UTC
    i need to open a template and write data into that. i dont need to open a new .xlsx file. With Spreadsheet::WriteExcelXML is it possible to open a existing file?

    You said you need to open a template file. Usually, that implies making a new file based on the template. And writing back to the same file makes the template not a template any more.

    But, it is possible to write the data back to the original file:

    # open file in read/write mode open(my $xlshandle, '+<', $xlsfile) or die "Can't open '$xlsfile' for +read/write: $!\n"; binmode($xlshandle); # insert code to read spreadsheet # reset handle to beginning of file seek($xlshandle, 0, 0); my $newxls = Spreadsheet::WriteExcelXML->new($xlshandle); # handle, NO +T file # insert code to put updated data into $newxls $newxls->close(); close($xlshandle);

    BUT, it's much safer to:

    my $newxlsfile = $xlsfile . '.new'; my $newxls = Spreadsheet::WriteExcelXML->new($newxlsfile); # file, NOT + handle # insert code to put updated data into $newxls $newxls->close(); close($xlshandle); rename($xlsfile, $xlsfile . '.bak'); rename($newxlsfile, $xlsfile);

    You will still get a file with the same name as the original file, AND will have a back up of the original file.

    Update: added a call to binmode();