【发布时间】:2017-12-23 10:34:38
【问题描述】:
第一个表单数据插入得很好,但是当我尝试添加另一个字段时,它会被覆盖。如何让它添加到工作表的新行中?
当我再次运行代码并提交表单时,新值必须存储在 Excel 工作表的下一行中。
这是我的代码:
<form action="write_excel.php" method="post">
<input type="text" name="fname" id="fname"/>
<input type="text" name="lname" id="lname"/>
<input type="email" name="email" id="email"/>
<textarea name="des" id="des"></textarea>
<button type="submit" value="submit">Submit</submit>
</form>
<?php
$name1=$_POST['fname'];
$name2=$_POST['lname'];
$email=$_POST['email'];
$des=$_POST['des'];
//The Header Row
$Header = array('Firstname', 'LastName','email','Designation');
$data = array();
//Data to be written in the excel sheet -- Sample Data
array_push($data, array($name1 ,$name2,$email,$des));
$filename = write_excel1($data, $Header);
function write_excel1($data, $Header)
{
//We are using PHPExcel Library for creating the Microsoft Excel file
require_once './PHPExcel/Classes/PHPExcel.php';
$objPHPExcel = new PHPExcel();
//Activate the First Excel Sheet
$ActiveSheet = $objPHPExcel->setActiveSheetIndex(0);
//Write the Header
$i=0;
foreach($Header as $ind_el)
{
//Convert index to Excel compatible Location
$Location = PHPExcel_Cell::stringFromColumnIndex($i) . '1';
$ActiveSheet->setCellValue($Location, $ind_el);
$i++;
}
//this piece of code use to add rows in excel sheet.
//Insert that data from Row 2, Column A (index 0)
$rowIndex=2;
// echo $rowIndex;
$columnIndex=0; //Column A
foreach($data as $row)
{
foreach($row as $ind_el)
{
$Location = PHPExcel_Cell::stringFromColumnIndex($columnIndex) . $rowIndex;
//var_dump($Location);
$ActiveSheet->setCellValue($Location, $ind_el); //Insert the Data at the specific cell specified by $Location
$columnIndex++;
}
$rowIndex++;
}
//1. Mark the Header Row in Color Red
$Range = 'A1:B1:C1:D1';
$color = 'FFFF0000';
$ActiveSheet->getStyle($Range)->getFill($Range)->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB($color);
//2. Set the Column Width
for($i=0; $i<count($Header);$i++)
{
$Location = PHPExcel_Cell::stringFromColumnIndex($i) ;
$ActiveSheet->getColumnDimension($Location)->setAutoSize(true);
}
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
//Result File name
$objPHPExcel = PHPExcel_IOFactory::load("myfile.xlsx");
$objWriter->save('myfile.xlsx');
}
?>
【问题讨论】:
-
首先您必须使用 php excel
$highestRow = $objPHPExcel->setActiveSheetIndex(0)->getHighestRow();获得最大rowindex,然后在其中添加 +1 并添加下一个提交的表单字段。 -
非常感谢您的及时回复...但我对 php 真的很陌生。你能展示一下它是怎么做的吗?