PHP uses AJAX to export CSV or Excel (thinkphp) methods

Source: Internet
Author: User

First of all I highly recommend to see this article you will export files set to CSV format file The actual test export CSV file speed is 10 times of the Excel file about

First, let me introduce the method of exporting CSV file:

If you are simply on the data export interface via the user click Generate CSV or Excel button through the server to the browser output Excel or CSV if the data volume is small can use such a method (this method cannot use Ajax) online Baidu a bunch of introduction

Here are more detailed method introduction and source code

What I'm introducing here is that when the volume of data is larger, such as generating Excel or CSV files, it may take a few minutes for the user to click on the Generate button to make a loading box to prevent users from randomly clicking the Excel or CSV file into the

Server-side and then return to the browser via the Ajax method after a user clicks to download the file

1. Exporting CSV is simple

Core Generation Code :

The $data passed in here is a two-dimensional array

That is $data = (array, array,array)

function Create_csv ($data, $filename = ' Simple.xls ')

{

Ini_set (' max_execution_time ', ' 0 ');

The CSV here is a new CSV folder under your project's root directory

$path = (' csv/'. Iconv (' UTF-8 ', ' gb2312 ', $filename));

$fp = fopen ($path, ' w ');

foreach ($data as $k = $v)

{

foreach ($v as $key = & $value)

{

Encode data values in code to avoid Chinese garbled problems

$value = Iconv (' UTF-8 ', ' gb2312 ', $value);

}

Fputcsv ($fp, $v); }

Fclose ($FP);

$result = Array (' status ' = = 1, ' path ' = ' csv/'. $filename);

return $result;

Exit

}

Background Call Code:

Public function Generate ()

{

Here data needs to be processed for two-dimensional data and eventually for $data = (Array,array,array) such

$data = Array ();

$excel _title = Array ("_id", "Bo_subject",);

Array_push ($data, $excel _title);

... Process real data and push it into $data

$result = Create_csv ($data, $filename);

$this->ajaxreturn ($result);

}

The front desk posts via jquery: It is recommended to study layer this pop-up layer component is especially nice. Portal

Code:

<button style= "float:right;" class= "btn" id= "Generate" Url= "{: U (' Generate ')}" > Build </button>

$ (' #generate '). Click (Function (Event)

{

var url = $ (this). attr (' url ');

Loading layer

var index = layer.load (1);

function Download (content)

{

Layer.open ({

Type:1,

Content:content,

Skin: ' Layui-layer-demo ',

Style class name

Closebtn:1,

shift:0,

Area: [' 200px ', ' 105px '],

Shadeclose:true,

Open Mask off

Content:content}); }

$.post (URL, function (data) {

if (data.status)

{

Layer.close (index);

Data.path = ' __root__ ' + '/' + (Data.path);

var test = ' <a class= ' download ' href = ' + data.path + ' target= ' _blank ' > click to download </a> ';

Download (test); }

else {

Layer.close (index);

Layer.alert (' Error occurred ')}}, "JSON"); });

2. Export Excel: (export Excel especially slow scenario for more complex issues such as export font color size typesetting control and export pictures, etc.)

First of all we need to introduce phpexcel this plug-in after downloading, remove unnecessary put in/thinkphp/library/vendor/phpexcel

Note that the directory structure is

The core functions are:

function Create_xls ($data, $filename = ' Simple.xls ')

{

Ini_set (' max_execution_time ', ' 0 ');

Vendor (' Phpexcel.phpexcel ');

$phpexcel = new Phpexcel ();

$phpexcel->getproperties ()->setcreator ("Hyz")->setlastmodifiedby ("Hyz")->settitle ("Office. XLSX Test Document ")->setsubject (" Office "XLSX Test Document")->setdescription ("Test document for Office Generated using PHP classes. ") ->setkeywords ("Office openxml PHP")->setcategory ("11111");

$phpexcel->getactivesheet ()->fromarray ($data);

$phpexcel->setactivesheetindex (0);

$objWriter = new phpexcel_writer_excel2007 ($phpexcel);

Note that there is a Chinese encoding before the transmission of the need for a Chinese code

$filePath = ' csv/'. $filename. Xlsx ';

$objWriter->save ($filePath);

$result = Array (' success ' = = True, ' url ' = = $filePath);

return $result;

Exit

}

The rest of the sections can be referenced in the same way as CSV generation

PHP uses AJAX to export CSV or Excel (thinkphp) methods

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.