PHP: ParseCSV or PHPExcel which is better? - php

I want to create an application that when you import the CSV then it will export to .xlsx. But there are some conditins:
I need to change the column order and remove some of the columns when its exported
I need also to change the color and font(size,color)
And also create a multiple worksheets on single .xlsx file.
Which is better to use on this kind of application, can anybody help me and share some points which is better. I do the exploring on both but I need some guidance and some better solutions. Thank you.

// output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=file.csv');
// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');
// output the column headings
fputcsv($output, array('First Name', 'Last Name'));
You dot need to use a plugin or anything. PHP has the functionality within itself. What i wrote above is an example of defining the file and outputting the first row of the CSV.
Each use of fputcsv() outputs a new row.
So you can define the order of things by telling it in the array which value goes where in the row.

Related

PHP: Create an excel table

I need to create an excel table with help of php. Is that possible? The php code below creates and write to an excel file. I would like to create an excel table with the data, see picture below. I'm using PhpSpreadsheet (sorry I forgot to say that)
Edit: The code below uses library PhpSpreadsheet to ceate a excel file with some content.
I want to create an excel table:
The code works and create the content as the second picture below shows. This is NOT an excel table, just plain text in cells.
But that is not what I want. I want to be able to create the content as the first picture below shows. This is an excel table. When you create an excel table by hand you can choose colrs etc. I do not care about the colors. Excel add the column name and push the content down.
What I have tried is to add: $sheet->setAutoFilter('A1:B5'); to the code, but this does not create an excel table as shown in the third picture below.
So the question is: What do I need to add to the code above to be able to create the content as shown in the first picture below
The fourth picture below shows how to crate an excel table in excel (and this is what I want the php code to do)
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'A1');
$sheet->setCellValue('A2', 'A2');
$sheet->setCellValue('A3', 'A3');
$sheet->setCellValue('A4', 'A4');
$sheet->setCellValue('A5', 'A5');
//$sheet->setCellValue('A6', 'A6');
$sheet->setCellValue('B1', 'B1');
$sheet->setCellValue('B2', 'B2');
$sheet->setCellValue('B3', 'B3');
$sheet->setCellValue('B4', 'B4');
$sheet->setCellValue('B5', 'B5');
$writer = new Xlsx($spreadsheet);
$writer->save('CreateExcelTable.xlsx');
The picture below show the tableI would like to create
With the code above this is created:
With the code added:
$sheet->setAutoFilter('A1:B5');
The picture below show what is created.It is not a table
Insert/Table is simply a GUI "shortcut" method for styling and setting autofilters against a block of cells. Both of these can be done as individual tasks using PHPSpreadSheet, but the library does not provide a "shortcut" way of doing this with a single method call.
Take a look at section of the Developer documentation.
I have a similar problem.
My Excel Template had some array formulas that refer to Named Data Tables,
(instead of writing in the array formula A2:A150 i would simply write NameOfMyTable[NameOfColumn])
When i inserted some data in my template using PhpSpreadSheet and downloaded the produced excel file, Each instance of NameOfMyTable[NameOfColumn] was replaced with REF!
Instead of searching how make or preserve Named Data Tables while using PHPSpreasheet. I simply converted all my Named tables back to simple ranges. (you can easily do this conversion through TableTools in excel without having to change every formula in your Excel Template).
I have a code I wrote, use it if you want
look at the code
using
$excelExport = new ExcelExport(['name' => 'dılo'], 'file');
$excelExport->download();
shortest excel creation example with php
basic example
<?php
$file="demo.xls";
$test="<table ><tr><td>Cell 1</td><td>Cell 2</td></tr></table>";
header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=$file");
echo $test;
?>

Print contents of a mysql table in txt format

I am working on a web application (php, javascript, html) that holds a large amount os user information. It is designed for temporary jobs.
The thing is, I have three tables (mysql) with information about the users. One for the address and other things, other for driver license, certificates, ..., and the last one for user experience.
What I want to do, is have a "print" button that generates a txt file with all that data in one file. The thing is that I alredy have an idea of how to do it.
1) retrieve all the information for the tables in a join with username.
2) I already had the function to "resource_to_array" for building an array with all the data
3) I could just go for each column of the array and saving the information that I want
But what I am asking is for experience doing something like this. This is the first time for me, and I want it to make it good and scalable for the future.
How will be a good way to do implement it? also, how could I create a plain text with all that information? (this part is in where I have more doubts about)
I know that maybe is a weird question..but I do not want code, I just want a vision for the implementation. Also, is there is a library os something similar that do what I want to do
Thank you very much.
First of all make a link that will generate text file.
Print
Now, in print.php you have to put your logic.
Execute the join Query for fetching the data.
Fetch "array" for building an array with all the data.
Get the element from the array that you want to save in text file.
Now logic is here, Use file handling for creating the text file with save data.
Logic is here(print.php) :
<?php
$conn = new mysqli("host-name","username","password","database-name");
$query = "....";
$result = $conn->query($query);
$rs = $result->fetch_array(MYSQLI_BOTH);
while($rs = $result->fetch_array(MYSQLI_BOTH))
{
$data = $rs['column-name']; // data you want to save in text file
$f = fopen("save.txt", 'a');
fwrite($f, $data);
fclose($f);
}
$filename = "save-data.txt"; // name of the file you want to download on clicking the link
$file = "save-data.txt";
$type = filetype($file);
// Send file headers
header("Content-type: $type");
header("Content-Disposition: attachment;filename=$filename");
header("Content-Transfer-Encoding: binary");
header('Pragma: no-cache');
header('Expires: 0');
// Send the file contents.
set_time_limit(0);
readfile($file);
?>
Sidenote: The a switch appends to file. If you do not wish to keep adding to it, use the w switch:
$f = fopen("save.txt", 'w');
I hope it will help you.

how to format exported excel sheet with column color in php?

i have export a excel sheet which will collect data from my customer table (Mysql database) now i want to format it with column color.
here is my code to export excel sheet....
<?php
ob_start();
session_start();
include("include/session.php");
include("common_function.php");
//connect the database
$customer_id=$_GET['pid'];
//Enter the headings of the excel columns
$contents="Sr.,Agent Name,Contact Person,Contact Number,Password,Deal With Customer,References,Time to reach,Package Offered,Mode of Payment,Note,NEAREST CROSS STREET,DATE OF BIRTH\n";
//Mysql query to get records from datanbase
//You can customize the query to filter from particular date and month etc...Which will depends your database structure.
$sql = "SELECT id,agent_id,fname1,mobile_no,password,fname,rentfrom,cheque_no,package_id,monthly_monitoring,final_comment,cross_street,dob1 FROM customer WHERE `id`='$customer_id'";
$user_query = mysql_query($sql);
//While loop to fetch the records
while($row = mysql_fetch_array($user_query))
{
$contents.=$row['id'].",";
$contents.=$row['agent_id'].",";
$contents.=$row['fname1'].",";
$contents.=$row['mobile_no'].",";
$contents.=$row['password'].",";
$contents.=$row['fname'].",";
$contents.=$row['rentfrom'].",";
$contents.=$row['cheque_no'].",";
$contents.=$row['package_id'].",";
$contents.=$row['monthly_monitoring'].",";
$contents.=$row['final_comment'].",";
$contents.=$row['cross_street'].",";
$contents.=$row['dob1']."\n";
}
// remove html and php tags etc.
$contents = strip_tags($contents);
//header to make force download the file
header("Content-Disposition: attachment; filename=Sale_report".date('d-m-Y').".csv");
print $contents;
?>
now i want to color my first row...
Heay Cnik,
Ayyappan Sekar is right.
PHPExcel is a library that can be used to generate xls( and many other formats ) file. Its purpose is to generate a file and not sending it on some id.
What you can do is, first generate a file using PHPExcel library and save it somewhere.
For sending email to some id, you can use http://php.net/manual/en/function.mail.php'>mail function. However, its little complex to send emails with attachments using php's mail function though not very difficult.
Refer the links given below:
1] http://www.shotdev.com/php/php-mail/php-send-email-upload-form-attachment-file/
2] Attach File Through PHP Mail (refer to the answer of asprin)
3] http://www.texelate.co.uk/blog/send-email-attachment-with-php/
The CSV file is a simple text file, you can't format it with color
http://en.wikipedia.org/wiki/Comma-separated_values
Hi instead of using header to export to excel, U can use PHPExcel library. It provides much easier inbuilt methods to achieve what u want.. even u can apply styles, merge cells etc

how do I organise a downloadable csv file in php

What I am doing is allowing my client to download a CSV file of all their orders in the database. That I can do, but what I can't seem to figure out if how to organise that file so that the information is clear and easy to understand in the file itself.
Here is my working code that creates the file for download:
$today = date("d-m-Y");
// output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=orders_' . $today . '.csv');
// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');
// output the column headings
fputcsv($output, array('Product ID & Qty','First Name', 'Last Name', 'Total Spent', 'Payment Date'));
// fetch the data
include('../storescripts/connect_to_mysql.php');
$rows = mysql_query('SELECT product_id_array, first_name, last_name, mc_gross, payment_date FROM transactions ');
// loop over the rows, outputting them
while ($row = mysql_fetch_assoc($rows)) fputcsv($output, $row);
The columns are being created with the headings listed above, but almost all the information is squeezed into the first column and the rest is just spread over the other columns. It looks a mess and wouldn't make much sense to anyone.
I was wondering if there was a way to force which row of data goes into each column.
Thanks in advance.
By default, when Excel reads a CSV, it won't automatically expand all of the columns so the data can look as if there's something wrong with the CSV content itself, when actually you just need to configure Excel or expand them manually.

PHP:Writing to excel file using PEAR

I have installed PEAR, Spreadsheet_Excel_Writer and OLE. The sample program is executed successfully but when I try to read the file it shows garbage values. I also tried $workbook->setVersion(8); and $worksheet->setInputEncoding('UTF-8');
I am using this tutorial and Google lot for this problem.
http://www.sitepoint.com/article/getting-started-with-pear/3/
Thanks in advance.
I try to use PEAR only when I really need to...you can easily generate an excel spreadsheet( assuming it's just data) with something like this:
$header = "Last Name\tFirst Name\tAge\tJob\n"; // new line is start of new row, tab is next column
//ideally you would get this from a DB and just loop through it and append on
$row1 = "Smith\tBob\t25\tManager\n";
$row2 = "Anderson\tTrent\t32\tCEO\n";
$excel = $header.$row1.$row2;
$xlsfile = "excel_example".date("m-d-Y-hiA").".xls";
header('Content-type: application/vnd.ms-excel');
header("Content-Disposition: attachment; filename=$xlsfile");
echo $excel;
that's just a tab seperated value file though and you're sending headers suggesting the browser treat that data as an excel file. so there's no formatting of data which the poster may require.

Categories