I'm using PHPExcel library for many Excel manipulations, combined with PHP/MySQL.
That helps me well.
But I can't figure how to split an Excel document sheet by sheet,where each sheet is created as a new Excel document.
I also need, at the same time, to delete the empty lines which are in the original document in the new Excel documents produced (cleaning up the final docs).
What's the best way to do it ?
All your experiences are greatly appreciated.
Best regards.
I have found the way of what I wanted.
Here is a solution (maybe not the best way, but it works fine enough) :
$file = $_POST['file'];
$filename = pathinfo($file, PATHINFO_FILENAME);
require_once 'phpexcel/Classes/PHPExcel.php';
$xls = new PHPExcel();
$xlsReader= new PHPExcel_Reader_Excel5();
$xlsTemplate = $xlsReader->load($file);
$sheet1 = $xlsTemplate->getSheetByName('Sheet1');
$xls->addExternalSheet($sheet1,0);
$xls->removeSheetByIndex(1);
$xlsWriter = new PHPExcel_Writer_Excel5($xls);
$xlsWriter->save($filename."_Sheet1.xls");
$sheet2 = $xlsTemplate->getSheetByName('Sheet2');
$xls->addExternalSheet($sheet2,0);
$xls->removeSheetByIndex(1);
$xlsWriter = new PHPExcel_Writer_Excel5($xls);
$xlsWriter->save($filename."_Sheet2.xls");
$sheet3 = $xlsTemplate->getSheetByName('Sheet3');
$xls->addExternalSheet($sheet3,0);
$xls->removeSheetByIndex(1);
$xlsWriter = new PHPExcel_Writer_Excel5($xls);
$xlsWriter->save($filename."_Sheet3.xls");
$sheet4 = $xlsTemplate->getSheetByName('Sheet4');
$xls->addExternalSheet($sheet4,0);
$xls->removeSheetByIndex(1);
$xlsWriter = new PHPExcel_Writer_Excel5($xls);
$xlsWriter->save($filename."_Sheet4.xls");
$sheet5 = $xlsTemplate->getSheetByName('Sheet5');
$xls->addExternalSheet($sheet5,0);
$xls->removeSheetByIndex(1);
$xlsWriter = new PHPExcel_Writer_Excel5($xls);
$xlsWriter->save($filename."_Sheet5.xls");
$sheet6 = $xlsTemplate->getSheetByName('Sheet6');
$xls->addExternalSheet($sheet6,0);
$xls->removeSheetByIndex(1);
$xlsWriter = new PHPExcel_Writer_Excel5($xls);
$xlsWriter->save($filename."_Sheet6.xls");
Then, my original Excel file, containing 6 sheets is now splitted in 6 Excel files, as I wanted.
As you can see, it was not so hard to release, but the documentation is so confusing...
Hope this can help.
Related
// but the code is throwing unexpected terminal operator new
function MovePokemon(argument0, argument1) {
old = argument0;
new = argument1;
TPartyID = global.PartyID[old]
global.PartyID[old] = global.PartyID[new]
global.PartyID[new] = TPartyID;
new is a keyword in the current versions of GameMaker, so you'll need to rename that variable (say, to _new).
The project in question may leave some to be desired given the complete absence of local variable declarations (var).
Try use this code in your script to avoid use "new"
function MovePokemon(argument0, argument1) {
TPartyID = global.PartyID[argument0]
global.PartyID[argument0] = global.PartyID[argument1]
global.PartyID[argument1] = TPartyID;
I have a problem with saving XML file from R.
Firstly I write my code here:
doc = newXMLDoc()
document = newXMLNode("Document", doc = doc)
set = newXMLNode("Settings", parent = document)
elements = newXMLNode("Elements", parent = set)
newXMLNode("Canvas", parent = elements, attrs = c(Id = "1"))
newXMLNode("Canvas", parent = elements, attrs = c(Id = "2"))
objcol = newXMLNode("ObjectCollection", parent = document)
timeSeries1 = newXMLNode("Timeseries", parent = objcol)
timeSeries2 = newXMLNode("Timeseries", parent = objcol)
saveXML(doc, file="test.dtv", indent = T,
prefix = '<?xml version="1.0" encoding="utf-8" standalone="no"?>\n')
So, if I save doc without prefix, all is good, but i haven't prefix in my ouput file. When I add prefix attribute to function saveXML, output is really bad. It has only one '\n' after prefix(because I write it in prefix string), but all document is on one line. I haven't ideas how to fix it.
Thank you for your attention.
So, I'am also quite surprised why this is not working, but found a "workaround" to it. Hope this is helpfull.
cat(saveXML(doc,
indent = TRUE,
prefix = "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"no\"?>\n"),
file="test.dtv")
I've been following this guide https://msdn.microsoft.com/EN-US/library/office/cc861607.aspx to insert a string to a cell in an excel file. The example is really confusing, and even when i copy/paste it doesn't work. I'm looking for a very simple example to insert a a value into a cell like:
spredSheet.InsertCell("A", 1, string value)
I could really use a simple code example showing me how to insert data into a cell using OpenXML in asp.net.
I tried the code from this post Using OpenXML to insert a datatable into excel, but it creates a broken excel file.
This is how my code look without the helper functions from the link
using (SpreadsheetDocument myDoc = SpreadsheetDocument.
Create(Server.MapPath("/data.xls"), SpreadsheetDocumentType.Workbook))
{
WorkbookPart workbookpart = myDoc.AddWorkbookPart();
workbookpart.Workbook = new Workbook();
// Add a WorksheetPart to the WorkbookPart.
WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
//add column names to the first row
Row header = new Row();
header.RowIndex = (UInt32)1;
SheetData sheetData = new SheetData();
Cell headerCell = createTextCell(1, 1, text);
header.AppendChild(headerCell);
sheetData.AppendChild(header);
// Add a WorkbookPart to the document.
worksheetPart.Worksheet = new Worksheet(sheetData);
}
The MSDN example is using SpreadsheetDocument.Open which opens an existing file but you are creating a brand new file with SpreadsheetDocument.Create. When you create a brand new file there are certain elements you must create in order for the file to be valid. The elements you are missing are the Sheets and Sheet elements.
Sheets are stored separately from the SheetData so you need to create a Sheet inside a Sheets and then associate the Sheets with the WorksheetPart.
This can be done like so:
Sheets sheets = myDoc.WorkbookPart.Workbook.AppendChild(new Sheets());
sheets.AppendChild(new Sheet()
{
Id = myDoc.WorkbookPart.GetIdOfPart(myDoc.WorkbookPart.WorksheetParts.First()),
SheetId = 1,
Name = "Sheet1"
});
So your full code listing would be something like:
using (SpreadsheetDocument myDoc = SpreadsheetDocument.
Create(Server.MapPath("/data.xls"), SpreadsheetDocumentType.Workbook))
{
WorkbookPart workbookpart = myDoc.AddWorkbookPart();
workbookpart.Workbook = new Workbook();
// Add a WorksheetPart to the WorkbookPart.
WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
//add column names to the first row
Row header = new Row();
header.RowIndex = (UInt32)1;
SheetData sheetData = new SheetData();
Cell headerCell = createTextCell(1, 1, text);
header.AppendChild(headerCell);
sheetData.AppendChild(header);
// Add a WorkbookPart to the document.
worksheetPart.Worksheet = new Worksheet(sheetData);
//this is the part that was missing from your code
Sheets sheets = myDoc.WorkbookPart.Workbook.AppendChild(new Sheets());
sheets.AppendChild(new Sheet()
{
Id = myDoc.WorkbookPart.GetIdOfPart(myDoc.WorkbookPart.WorksheetParts.First()),
SheetId = 1,
Name = "Sheet1"
});
}
//load the excel library
$this->load->library('excel');
//read file from path
$objPHPExcel = PHPExcel_IOFactory::load($file);
//get only the Cell Collection
$cell_collection = $objPHPExcel->getActiveSheet()->getCellCollection();
//extract to a PHP readable array format
foreach ($cell_collection as $cell) {
$column = $objPHPExcel->getActiveSheet()->getCell($cell)->getColumn();
$row = $objPHPExcel->getActiveSheet()->getCell($cell)->getRow();
$data_value = $objPHPExcel->getActiveSheet()->getCell($cell)->getValue();
//header will/should be in row 1 only. of course this can be modified to suit your need.
if ($row == 1) {
$header[$row][$column] = $data_value;
} else {
$arr_data[$row][$column] = $data_value;
}
}
This is my reader code. I'm not able to read the date in my Excel file using this code; it's returning the code like 030567 some thing.
My Excel file has the date value but this code is not returning the date. I don't know how to resolve this issue.
You need to use format like below code:
getCellByColumnAndRow($col, $row)->getValue())->format('m/d/Y');
Hope this will resolve your problem.
Or you can also try this:
$data_value = $objPHPExcel->getActiveSheet()->getCell($cell)->getValue();
$phpDateTimeObject = PHPExcel_Shared_Date::ExcelToPHPObject($data_value);
echo phpDateTimeObject->format('Y-m-d');
So, i have a form which able to read excel files and save to database by uploading an excel file. It is fine when i upload .xls file, but not with the .xlsx. Here is the code:
echo ' File berhasil diupload => '.$dok['file_name']; //success to echo uploaded .xlsx file
//EXCEL READING, load library
$this->load->library('excel');
//Identify the type of $inputFileName
$inputFileType = PHPExcel_IOFactory::identify(FCPATH."/asset/files/uploads/".$dok['file_name']);
//Create a new Reader of the type that has been identified
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
//Failed to echo (if i upload .xlsx file)
echo 'input file type => '.$inputFileType;
//begin to read excel file
$this->excel = $objReader->load(FCPATH."/asset/files/uploads/".$dok['file_name']);
$objWorksheet=$this->excel->getActiveSheet();
$highestRow=$objWorksheet->getHighestRow();
$highestColumm = $objWorksheet->getHighestColumn();
$highestColumm++;
//jika option timpa, maka delete semua data
if($timpa == 'y')
{
$this->_model->del_table_mcactivity();
}
//read per row and save to database
foreach($this->excel->getWorksheetIterator() as $worksheet){
$worksheetTitle = $worksheet->getTitle();
$highestRow = $worksheet->getHighestRow();
$highestColumn = $worksheet->getHighestColumn();
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
$nrColumns= ord($highestColumn) - 64;
for ($row = 2; $row <= $highestRow; ++ $row) {
$kodemak = $objWorksheet->getCell("A$row")->getValue();
$tahun = $objWorksheet->getCell("B$row")->getValue();
$unitkerja = $objWorksheet->getCell("C$row")->getValue();
$nomorkegiatan = $objWorksheet->getCell("D$row")->getValue();
$kegiatan = $objWorksheet->getCell("E$row")->getValue();
$noskkegiatan = $objWorksheet->getCell("F$row")->getValue();
$jenis = $objWorksheet->getCell("G$row")->getValue();
$pagu = $objWorksheet->getCell("H$row")->getValue();
//get for refworkingunit id
$idrefworkingunit = $this->_model->get_workingunit_by_name($unitkerja);
//filtering for budget
$budget = $this->filter_budget($pagu);
//grouping variable to save in database
$activity_data = array('year'=>$tahun, 'idrefworkingunit'=>$idrefworkingunit, 'activitynumber'=>$nomorkegiatan, 'activityname'=>$kegiatan, 'activityreference'=>$noskkegiatan, 'accountnumber'=>$kodemak, 'traveltype'=>$jenis, 'budget'=> $budget);
//insert to database
$this->db->insert('mcactivity', $activity_data);
}
}
I use PHPExcel_IOFactory::identify() to identify the reader should be used. But i think it's failed.I've read this question , then i replace
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
with:
$objReader = PHPExcel_IOFactory::createReader('Excel2007'); but it still doesn't work. Can somebody help me, please ?
XLS and XLSX are two different files types.
XLS
$this->load->library('Excel5');
XLSX
$this->load->library('Excel2007');
Consult the documentation "PHPExcel User Documentation - Reading Spreadsheet Files.doc" that comes with PHPExcel. Page 1 explains the formats, and Page 4 explains different ways of telling PHPExcel what file type to handle.
There are multiple lines where the reference to "Excel2007" and "Excel5" might occur.
Do a search on 'Excel' and not over-look any possibility.
e.g. $objReader = new PHPExcel_Reader_Excel2007(); //was Excel5
Change to _Excel2007 did allow me to read a .xlsx file, but did not break a script that read a .xls file. So there might be backwards compatibility.