fast-excel icon indicating copy to clipboard operation
fast-excel copied to clipboard

Why can't set the header of the exported table

Open hipig opened this issue 4 years ago • 16 comments

I look at the source code and find that the writeheader method is private,Is there any way I can customize the table header

hipig avatar Apr 03 '20 08:04 hipig

How to set custom style header:

<?php

namespace App\Http\Controllers;

use Box\Spout\Writer\Style\Color;
use Box\Spout\Writer\Style\StyleBuilder;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
use Rap2hpoutre\FastExcel\FastExcel;
use Rap2hpoutre\FastExcel\SheetCollection;


class Controller extends BaseController
{

    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    public function export()
    {
        $file = 'test-header-style.xlsx';

        $style = (new StyleBuilder())
            ->setFontBold()
            ->setBackgroundColor(Color::YELLOW)
            ->build();

        $list = collect([
            ['id' => 1, 'name' => 'Elminson', 'time' => time()],
            ['id' => 2, 'name' => 'Dan', 'time' => time()],
        ]);

        $sheets = new SheetCollection([
            'Users' => $list,
            'Second sheet' => $list
        ]);

        return (new FastExcel($sheets))->headerStyle($style)->export($file);

    }
}

elminson avatar Apr 07 '20 00:04 elminson

How to set custom style header:

<?php

namespace App\Http\Controllers;

use Box\Spout\Writer\Style\Color;
use Box\Spout\Writer\Style\StyleBuilder;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
use Rap2hpoutre\FastExcel\FastExcel;
use Rap2hpoutre\FastExcel\SheetCollection;


class Controller extends BaseController
{

    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    public function export()
    {
        $file = 'test-header-style.xlsx';

        $style = (new StyleBuilder())
            ->setFontBold()
            ->setBackgroundColor(Color::YELLOW)
            ->build();

        $list = collect([
            ['id' => 1, 'name' => 'Elminson', 'time' => time()],
            ['id' => 2, 'name' => 'Dan', 'time' => time()],
        ]);

        $sheets = new SheetCollection([
            'Users' => $list,
            'Second sheet' => $list
        ]);

        return (new FastExcel($sheets))->headerStyle($style)->export($file);

    }
}

I'm sorry. I think you misunderstood me. I mean I want to change the text of the head, not the style

hipig avatar Apr 07 '20 03:04 hipig

text header Screenshot at Apr 07 10-05-20 Do you mean that header ? This header you can change it on the collection, the header texts are the keys of the array

 $list = collect([
            ['id' => 1, 'name' => 'Elminson', 'time' => time()],
            ['id' => 2, 'name' => 'Dan', 'time' => time()],
        ]);

In this case id, name, time are the header no sure if this is what are you asking for, if not please provide image/example to help you.

elminson avatar Apr 07 '20 14:04 elminson

text header Screenshot at Apr 07 10-05-20 Do you mean that header ? This header you can change it on the collection, the header texts are the keys of the array

 $list = collect([
            ['id' => 1, 'name' => 'Elminson', 'time' => time()],
            ['id' => 2, 'name' => 'Dan', 'time' => time()],
        ]);

In this case id, name, time are the header no sure if this is what are you asking for, if not please provide image/example to help you.

Thank you for your answer. In fact, this is what I need

I look up the data from the database.

$users = User::where('status', true)->get(['id', 'name', 'phone']);

Then I need to change some fields, such as changing to uppercase, such as changing to other languages.

According to your statement, I need to query the data and have a cycle.

$list = [];
$users->each(function ($item, $key) use ($list) {
     $list[$key]['Id'] = $item['id'];
     $list[$key]['Name'] = $item['name'];
     $list[$key]['Phone'] = $item['phone'];
});

It's not very friendly. I hope there is a way

(new FastExcel($users))->setHeader([
      'id' => 'Id',
      'name' => 'Name',
      'phone' => 'Phone'
])->export('file.xlsx');

hipig avatar Apr 10 '20 07:04 hipig

In this case you need to change the header from 'id' to 'Id' 'name' to 'Name' 'phone' to 'Phone' or to another language 'id' to 'Id' 'name' to 'Nombre' 'phone' to 'Telefono' Before export?

(new FastExcel($users))->setHeader([
      'id' => 'Id',
      'name' => 'Nombre',
      'phone' => 'Telefono'
])->export('file.xlsx');

If that is the case I can work on that feature but I don't warranty that will be merge to master branch, so you will have to use a different branch :).

I will work with friend https://gist.github.com/nycosborne to see when we can do this.

elminson avatar Apr 10 '20 14:04 elminson

Hi @hipig you can see this functionality on this PR https://github.com/elminson/fast-excel/tree/elminson_0000_with_custom_header You can clone my repo and switch branch (also you can see the code and include in your local vendor) I hope @rap2hpoutre like it and merge it

elminson avatar Apr 11 '20 00:04 elminson

@hipig check this out

Export large collections with chunk

->withCustomHeader

->setCustomHeader

  • combine this 2 methods and you can set header on collection before export

$collectionsOriginal = [
			collect([
				['col1' => 'row1 col1', 'col2' => 'row1 col2', 'col3' => 'row1 col3'],
				['col1' => 'row2 col1', 'col2' => 'row2 col2', 'col3' => 'row2 col3'],
				['col1' => 'row3 col1', 'col2' => 'row3 col2', 'col3' => 'row3 col3'],
			])
		];
		
		$file = __DIR__.'/test_custom_header.xlsx';
		$sheets = new SheetCollection($collectionsOriginal);
		(new FastExcel($sheets))->withCustomHeader(true)
								->setCustomHeader([
									'Id',
									'Nombre',
									'Telefono'
								])->export($file);

elminson avatar Apr 11 '20 00:04 elminson

@elminson Thank you very much. That's what I want. I'll use it locally

hipig avatar Apr 11 '20 12:04 hipig

Your welcome!

elminson avatar Apr 12 '20 02:04 elminson

@elminson I was very pleased to use this library...really simplified my life :) I just have one question: I installed the library using "composer require rap2hpoutre/fast-excel", after which (to use custom headers that you made and which I really need) I included the needed code in my local vendor. So, my question is: can custom headers be used on my development server and if yes would I also have to add changes manually in code as I did locally or is there another way?

ghost avatar May 04 '20 14:05 ghost

@lelisa13 Im glad to help you, and basically yes, also you can clone my repo and switch branch and move the content to your vendor folder, also you can do a script to clone the repo and switch branch after deployment (if you plan to use this feature on prod server). Another alternative is that @rap2hpoutre merge this branch to the current repo and then you just have to install using composer.

Let me know if you need any other guide, I will help you!

elminson avatar May 04 '20 14:05 elminson

@elminson thanks, you confirmed the things I had in mind, but was not sure about. If @rap2hpoutre could merge the branch, would be perfect. Otherwise, I can also do a script as you suggested, for my production environment. Thank you!!!

ghost avatar May 04 '20 15:05 ghost

Call to undefined method Rap2hpoutre\FastExcel\FastExcel::withCustomHeader()

eraporsmk avatar Jul 06 '20 20:07 eraporsmk

Is it possible to implement this @rap2hpoutre ? Also in some sheets, you may want to have multiple headers but there is no direct exposure to writer interface to enable writing custom data yourself before or after the row data.

If there can be a before and after callback callable parameter which the writer object will be passed to, problem solved.

xwiz avatar Apr 15 '21 23:04 xwiz

You can do it like mine!

$header = ['ID', 'NAME', ];  // this is my custom header

function usersGenerator() use ($header){
    yield $header;  // yield custom header
    foreach (User::cursor() as $user) {
        yield $user;
    }
}

(new FastExcel(usersGenerator()))
    ->withoutHeaders()      // remove automatically added header
    ->export('test.xlsx');

demozx avatar May 06 '22 12:05 demozx

I cannot get the yield thing above to work, here is what simple work for me You need to change only first row keys in the collection

                $headers = [
                    'partner_name' => trans('partner'),
                    'shop_name' => trans('shop'),
                    'total_item' => trans('total_item'),
                    'total' => trans('total'),
                ];
                $results = $query->get(array_keys($headers));
                $results->transform(function(Model $item, $i) use ($headers) {
                    if ($i == 0) {
                        $header = array_values($headers);
                        return array_combine($header, $item->toArray());
                    }
                    return $item;
                });
                $file = (new FastExcel($results))->export($tempPath);

leekung avatar Nov 26 '22 01:11 leekung