PHP-based export to Excel or CSV (with UTF8, GBK encoding conversion) _php Tutorial

Source: Internet
Author: User
PHP Import into Excel garbled because UTF8 encoding in the XP system does not support all UTF8 encoding transcoding a perfect solution
Utf-8 Coding Case
PHP code
Copy CodeThe code is as follows:
Header ("Content-type:application/vnd.ms-excel; Charset=utf-8 ");
Header ("Pragma:public");
Header ("expires:0");
Header ("Cache-control:must-revalidate, Post-check=0, pre-check=0");
Header ("Content-type:application/force-download");
Header ("Content-type:application/octet-stream");
Header ("Content-type:application/download");
Header ("Content-disposition:attachment;filename=11.xls");
Header ("Content-transfer-encoding:binary");
?>

PHP code
Copy CodeThe code is as follows:
$filename = "PHP Import to Excel-utf-8 encoding";
$filename =iconv ("Utf-8", "gb2312", $filename);
echo $filename;
?>

GBK Coding Case
PHP code
Copy CodeThe code is as follows:
Header ("Content-type:application/vnd.ms-excel; Charset=utf-8 ");
Header ("Pragma:public");
Header ("expires:0");
Header ("Cache-control:must-revalidate, Post-check=0, pre-check=0");
Header ("Content-type:application/force-download");
Header ("Content-type:application/octet-stream");
Header ("Content-type:application/download");
Header ("Content-disposition:attachment;filename=11.xls");
Header ("Content-transfer-encoding:binary");
?>

PHP code
Copy CodeThe code is as follows:
0. 0. $filename = "PHP Import to Excel-utf-8 encoding";
0.echo $filename;
0.?>

Download to Excel when you visit the website
To make the cell difference.
You can use a table table to make a Web page.
====================== Other methods =============================
1. Make Simple Excel
Copy CodeThe code is as follows:
0. 0.header ("Content-type:application/vnd.ms-excel");
0.header ("Content-disposition:filename=php2excel.xls");
0.
0.echo "a1/t b1/t c1/n";
0.echo "a2/t b2/t c2/n";
0.echo "a3/t b3/t c3/n";
0.echo "a4/t b4/t c4/n";
0.?>

2. Make a simple CSV
Copy CodeThe code is as follows:
$action =$_get[' action '];
if ($action = = ' Make ') {
$fp = fopen ("Demo_csv.csv", "a"); Open the CSV file and create it if it does not exist
$title = Array ("First_Name", "last_name", "Contact_email", "telephone"); First row of data
$data _1 = Array ("42343", "423432", "4234", "4234");
$data _2 = Array ("4234", "last_name", "Contact_email", "telephone");
$title = Implode (",", $title); Use ' Split into string '
$data _1 = Implode (",", $data _1); Use ' Split into string '
$data _2 = Implode (",", $data _2); Use ' Split into string '
$data _str = $title. " /r/n ". $data _1." /r/n ". $data _2." /r/n "; Add line break
Fwrite ($fp, $data _str); Write Data
Fclose ($FP); Close file handle
echo "Build Success";
}
echo "
";
echo "Generate CSV file";
?>

You can also do a closed function:
closed function One:
Copy CodeThe code is as follows:
function Exporttocsv ($csv _data, $filename = ' export.csv ') {
$csv _terminated = "/n";
$csv _separator = ",";
$csv _enclosed = ' "';
$csv _escaped = "//";
Gets the data from the database
$schema _insert = ";
$out = ";
Format the data
foreach ($csv _data as $row)
{
$schema _insert = ";
$fields _cnt = count ($row);
Printr ($row);
$tmp _str = ";
foreach ($row as $v)
{
$tmp _str. = $csv _enclosed.str_replace ($csv _enclosed, $csv _escaped. $csv _enclosed, $v). $csv _enclosed. $csv _separator;
}//End for

$tmp _str = substr ($tmp _str, 0,-1);
$schema _insert. = $tmp _str;
$out. = $schema _insert;
$out. = $csv _terminated;
}//End While
Header ("Cache-control:must-revalidate, Post-check=0, pre-check=0");
Header ("Content-length:".) Strlen ($out));
Header ("Content-type:text/x-csv");
Header ("Content-disposition:filename= $filename");
Echo $out;
}
/*
$csv _data = Array (Array (' Name ', ' Address ');
Array_push ($csv _data, Array ($row [' name '], $row [' address ']);
...
Exporttocsv ($csv _data, ' new_file.csv ');
*/

closed function Two:
Copy CodeThe code is as follows:
/**
* Simple class to properly output CSV data to clients. PHP 5 has a built
* In method to does the same for writing to files (Fputcsv ()), but many times
* Going right-to-the-client is beneficial.
*
* @author Jon Gales
*/
Class Csv_writer {
Public $data = Array ();
Public $deliminator;
/**
* Loads data and optionally a deliminator. Data is assumed to being an array
* of associative arrays.
*
* @param array $data
* @param string $deliminator
*/
function __construct ($data, $deliminator = ",")
{
if (!is_array ($data))
{
throw new Exception (' Csv_writer only accepts data as arrays ');
}
$this->data = $data;
$this->deliminator = $deliminator;
}
Private Function Wrap_with_quotes ($data)
{
$data = preg_replace ('/' (. +) "/', '" "$" "" ', $data);
return sprintf (' "%s" ', $data);
}
/**
* Echos the escaped CSV file with chosen Delimeter
*
* @return void
*/
Public function output ()
{
foreach ($this->data as $row)
{
$quoted _data = array_map (Array (' Csv_writer ', ' wrap_with_quotes '), $row);
Echo sprintf ("%s/n", implode ($this->deliminator, $quoted _data));
}
}
/**
* Sets proper Content-type header and attachment for the CSV OUTPU
*
* @param string $name
* @return void
*/
Public function Headers ($name)
{
Header (' content-type:application/csv ');
Header ("content-disposition:attachment; filename={$name}.csv ");
}
}
/*
$data = Array ("One", "one", "one", "three"), Array (4,5,6));
$data [] = Array ("One", "one", "three");
$data [] = array (4,5,6);
$csv = new Csv_writer ($data);
$csv->headers (' Test ');
$csv->output ();
*/

3. Using the Excel Class
Copy CodeThe code is as follows:
Require_once ' spreadsheet/writer.php ';
$workbook = new Spreadsheet_excel_writer ();
/* Generate CSV
$filename = Date (' Ymdhis '). CSV ';
$workbook->send ($filename); Send Excel file name for download
*/
Build Excel
$filename = Date (' Ymdhis '). XLS ';
$workbook->send ($filename); Send Excel file name for download
$workbook->setversion (8);
$workbook->setbiff8inputencoding (' UTF-8 ');
$worksheet =& $workbook->addworksheet ("Sheet-1");
$data []= Array (' ID ', ' username ', ' company ', ' email ', ' mob ', ' daytime ', ' intent ');
$data [] = array (1, ' Old beam ', ' * * studio ', ' jb51.net ', ' 1363137966* ', Time (), ' Y ');
$total _row = count ($data);
$total _col = count ($data [0]);
for ($row = 0; $row < $total _row; $row + +) {
for ($col = 0; $col < $total _col; $col + +) {
$worksheet->writestring ($row, $col, $data [$row] [$col]); Writing data in Sheet-1
}
}
/*
$worksheet =& $workbook->addworksheet ("Sheet-2");
$data []= Array (' ID ', ' username ', ' company ', ' email ', ' mob ', ' daytime ', ' intent ');
$data [] = array (1, ' Old beam ', ' * * studio ', ' jb51.net ', ' 1363137966* ', Time (), ' Y ');
$total _row = count ($data);
$total _col = count ($data [0]);
for ($row = 0; $row < $total _row; $row + +) {
for ($col = 0; $col < $total _col; $col + +) {
$worksheet->writestring ($row, $col, $data [$row] [$col]); Writing data in Sheet-2
}
}
*/
$workbook->close (); Complete the download
?>

Class Two
-----function Description
Reading Excel files
function Read_excel_file ($ExcelFile, $Result)
$ExcelFile Excel file name
Results returned by $Result
function return value returns 0 normally, otherwise an error message is returned
Returns an array of values
$result [sheet name] [row] [column] value is the value of the corresponding Excel cell

Create an Excel file
function Create_excel_file ($ExcelFile, $Data)
$ExcelFile Excel file name
$Data Excel Tabular Data
Please write the function at the beginning of the PHP script
Example 1:
Copy CodeThe code is as follows:
Require "excel_class.php";
Read_excel_file ("Book1.xls", $return);
for ($i =0; $i {
for ($j =0; $j {
echo $return [sheet1][$i] [$j]. "|";
}
Echo "
";
}
?>

Example 2:
copy code code such as Under:
!--? require "excel_class.php";
Read_excel_file ("Book1.xls", $return);
Create_excel_file ("Ddd.xls", $return [Sheet1]);
?>

http://www.bkjia.com/phpjc/327836.html www.bkjia.com True http://www.bkjia.com/phpjc/327836.html techarticle PHP Import into Excel garbled because UTF8 encoding in the XP system does not support all UTF8 encoding transcoding a perfect solution to the Utf-8 code case PHP code copy code is as follows:? PHP header ("Cont ...

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.