Convert Xlxs file to Csv using Phpspreadsheet - phpspreadsheet

I have a problem here, I want to upload Excel file to convert into CSV.
After submitting, my code only creates Csv file with empty data on it, (blank rows). Here is what I wrote:
require './vendor/autoload.php';
// get the upoloaded file
$excelFile = $_FILES["excelFile"]["tmp_name"];
$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader("Xlsx");
$spreadsheet = $reader->load($excelFile);
// write into csv
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, "Csv");
$writer->save("upload-file.csv");

You should use for the writer
$writer = new \PhpOffice\PhpSpreadsheet\Writer\Csv($spreadsheet);
$writer->setEnclosureRequired(false);
$writer->save("upload-file.csv");
Read more in the documentation

Related

PhpSpreadsheet: write entire workbook to file

I am reading an .xls template, and writing some data to the first sheet. When saving, I wish a copy of the entire workbook to be saved, but only the first sheet is being included.
How to save the entire workbook to file?
Existing code:
$template_file_type = IOFactory::identify($path);
$reader = IOFactory::createReader($template_file_type);
$excel_obj = $reader->load($path);
$excel_obj->setActiveSheetIndex(0);
$sheet = $excel_obj->getActiveSheet();
// writing to sheet
$objWriter = new Xlsx($excel_obj);
$objWriter->save($target_dir);
(Am aware I am reading .xls and writing .xlsx, but I haven't had trouble with that before...)

Can I read and write xslm files with php?

Can I read and write an xlsm file with PHPSpreadsheet i did it with xlsx files.
this is my code
<?php
require 'vendor/autoload.php';
$inputFileName = 'excels/file.xlsm';
/** Load $inputFileName to a Spreadsheet object **/
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($inputFileName);
//get first sheet in the workbook
$inputSheet = $spreadsheet->getSheet(0);
//Edit cell D4 with number 10 on first sheet
$inputSheet->setCellValue('D4', 10);
//Save file as result.xls
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
$newFileName = time();
$writer->save("excels/$newFileName.xlsm");
?>
No, I'm afraid you can't; PHPSPreadsheet doesn't support xlsm format for reading or for writing, although it is capable of reading some xlsm files

Using an existing spreadsheet as a template PHPspreadsheet

Objective
I want to use an existing Excel sheet, as a template to create an invoice.
Cell styling, such as coloring have to be included
An image (logo) has to be included
Standard data such as company address has to be included
I've read something about cfspreadsheet, but I'm not entirely sure how to use it.
Question A:
Is there a way to use a template file? Or do you know any alternatives?
Question B
Is it possible to use $_POST data with this library?
Example
$data = $_POST['example'];
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', '$data');
I am not 100% sure, but according to PhpSpreadsheet's doc, you can read a local file (your pre-made template) with :
$inputFileName = './sampleData/example1.xls';
/** Load $inputFileName to a Spreadsheet Object **/
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($inputFileName);
Or in case you already know the file type (.xlsx or .xsl) :
$inputFileType = 'Xls'; // Xlsx - Xml - Ods - Slk - Gnumeric - Csv
$inputFileName = './sampleData/example1.xls';
/** Create a new Reader of the type defined in $inputFileType **/
$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
/** Load $inputFileName to a Spreadsheet Object **/
$spreadsheet = $reader->load($inputFileName);
You can also wrap all of that in a try catch if you want.
Then you just have to make changes the same way you would populate a Spreadsheet you created, populating cells with data you get from pretty much where you want with php, examples :
Classic variable $foo = 'bar';
$_GET / $_POST / $_REQUEST
From a Database

How to read Microsoft Word Binary Data from database and convert it to readable text

I'm working in a java application called Mirth where I need to read a saved word document that is saved in a database table in a Microsoft word binary data format. Currently I can retrieve data from column in my java application but I need to convert this to readable text or XML or HTML format.
Looking online there is a java library call Aspose.words but I can't find any methods that would read in this binary data and convert it to something readable. Has anyone use Aspose.words before to do a task like this or does anyone have an alternative solution
Load document from Database
You can load the Word document using ByteArrayInputStream, if it's in a database table. Please refer to http://www.aspose.com/docs/display/wordsjava/How+to++Load+and+Save+a+Document+to+Database for an article that explains saving and reading a Word document to/from database. I have copied the relevant code from there.
public static Document readFromDatabase(String fileName) throws Exception
{
// Create the SQL command.
String commandString = "SELECT * FROM Documents WHERE FileName='" + fileName + "'";
// Retrieve the results from the database.
ResultSet resultSet = executeQuery(commandString);
// Check there was a matching record found from the database and throw an exception if no record was found.
if(!resultSet.isBeforeFirst())
throw new IllegalArgumentException(MessageFormat.format("Could not find any record matching the document \"{0}\" in the database.", fileName));
// Move to the first record.
resultSet.next();
// The document is stored in byte form in the FileContent column.
// Retrieve these bytes of the first matching record to a new buffer.
byte[] buffer = resultSet.getBytes("FileContent");
// Wrap the bytes from the buffer into a new ByteArrayInputStream object.
ByteArrayInputStream newStream = new ByteArrayInputStream(buffer);
// Read the document from the input stream.
Document doc = new Document(newStream);
// Return the retrieved document.
return doc;
}
Read text
Once the file is loaded, you can read it's paragraphs, tables, images etc using DOM, see the related documentation at http://www.aspose.com/docs/display/wordsjava/Programming+with+Documents.
But, if you just want to get all the text from a document, you can do it easily by calling toString() method as below
System.out.println(doc.toString(SaveFormat.TEXT));
I work with Aspose as Developer Evangelist.

Create and download word file from template in MVC

I have kept a word document (.docx) in one of the project folders which I want to use as a template.
This template contains custom header and footer lines for user. I want to facilitate user to download his own data in word format. For this, I want to write a function which will accept user data and referring the template it will create a new word file replacing the place-holders in the template and then return the new file for download (without saving it to server). That means the template needs to be intact as template.
Following is what I am trying. I was able to replace the placeholder. However, I am not aware of how to give the created content as downloadable file to user. I do not want to save the new content again in the server as another word file.
public void GenerateWord(string userData)
{
string templateDoc = HttpContext.Current.Server.MapPath("~/App_Data/Template.docx");
// Open the new Package
Package pkg = Package.Open(templateDoc, FileMode.Open, FileAccess.ReadWrite);
// Specify the URI of the part to be read
Uri uri = new Uri("/word/document.xml", UriKind.Relative);
PackagePart part = pkg.GetPart(uri);
XmlDocument xmlMainXMLDoc = new XmlDocument();
xmlMainXMLDoc.Load(part.GetStream(FileMode.Open, FileAccess.Read));
xmlMainXMLDoc.InnerXml = ReplacePlaceHoldersInTemplate(userData, xmlMainXMLDoc.InnerXml);
// Open the stream to write document
StreamWriter partWrt = new StreamWriter(part.GetStream(FileMode.Open, FileAccess.Write));
xmlMainXMLDoc.Save(partWrt);
partWrt.Flush();
partWrt.Close();
pkg.Close();
}
private string ReplacePlaceHoldersInTemplate(string toReplace, string templateBody)
{
templateBody = templateBody.Replace("#myPlaceHolder#", toReplace);
return templateBody;
}
I believe that the below line is saving the contents in the template file itself, which I don't want.
xmlMainXMLDoc.Save(partWrt);
How should I modify this code which can return the new content as downloadable word file to user?
I found the solution Here!
This code allows me to read the template file and modify it as I want and then to send response as downloadable attachment.

Resources