Tuzki
Tuzki

Reputation: 491

PHPEXCEL Set title for all worksheets

I'm trying to change the name of all the worksheets exported into xlsx from my code below. The export works fine, but the title of all the worksheets are just worksheet 1, 2, 3, etc

I want to grab the names from the column "asset_name" from my php database.

Eg, worksheet1->aaa

i want it to become: asset1-> aaa

Cheers,

/** Query 1.0 */
    $query = "SELECT * FROM asset_register";
    $query2 = "SELECT asset_name FROM asset_register";

    if ($result = mysql_query($query) or die(mysql_error())) {

    /** Create a new PHPExcel object 1.0 */
$objPHPExcel = new PHPExcel();
$objPHPExcel->getActiveSheet()->setTitle('Data');
}
/** Loop through the result set */
$rowNumber = 1; //start in row 1

$objPHPExcel->removeSheetByIndex(0);
while ($row = mysql_fetch_row($result)) {

    $newsheet = $objPHPExcel->createSheet();
    $col = 'A'; // start at column A

    $objPHPExcel->getActiveSheet()->setTitle(mysql_query($query2));

    foreach($row as $cell) {
        $newsheet->setCellValue($col.$rowNumber,$cell);
        $col++;
    }

Upvotes: 6

Views: 18377

Answers (2)

Jamuu
Jamuu

Reputation: 1

I did the almost the same thing but it doesn't give me a result. it just create one worksheet in excel with default name. i need a multiple worksheet from database tables with its name from tables.

  $query = "select name from campaigns WHERE clients_id='77'";



$result = mysqli_query($con,$query) or die(mysqli_connect_error());


$objPHPExcel = new PHPExcel();

$prevName = NULL;

$objPHPExcel->removeSheetByIndex(0);

while ($row = mysqli_fetch_row($result)){



 if ($row['name'] !== $prevName) {



$newsheet = $objPHPExcel->createSheet();





 $newsheet->setTitle($row['name']);

$prevName=$row['name'];

}

}

Upvotes: 0

Mark Baker
Mark Baker

Reputation: 212402

mysql_query($query2)

returns a resultset, so you're trying to set the worksheet label to a resource, not to a string. You need to fetch the row from the resultset to read the string value for asset_column as shown in all the MySQL documentation for PHP

EDIT

To give yourself a new sheet for each asset name, use something like:

$prevAssetName = NULL;
$objPHPExcel->removeSheetByIndex(0);
while ($row = mysql_fetch_row($result)) {
    if ($row['asset_name'] !== $prevAssetName) {
        $newsheet = $objPHPExcel->createSheet();
        $newsheet->setTitle($row['asset_name']);
        $prevAssetName = $row['asset_name'];
    }

    $col = 'A'; // start at column A
    foreach($row as $cell) {
        $newsheet->setCellValue($col.$rowNumber,$cell);
        $col++;
    }
}

Upvotes: 4

Related Questions