How to read data in Excel in Symfony2 liuggio Excel - excel

Hi I am new to Symfony2 and I need to upload Excel file to MYSQL database?
Can anyone send me a example of how to do it?
Thanks you
Raki

Start by adding: "CodePlex/PHPExcel": "1.7.7", to your composer.json file and updating.
Add a class to sit between the PHPExcel stuff and your code. Something like:
namespace Cerad\ArbiterBundle\Format;
class Excel
{
protected function createReaderForFile($fileName,$readDataOnly = true)
{
// Most common case
$reader = new \PHPExcel_Reader_Excel5();
$reader->setReadDataOnly($readDataOnly);
if ($reader->canRead($fileName)) return $reader;
// Make sure have zip archive
if (class_exists('ZipArchive'))
{
$reader = new \PHPExcel_Reader_Excel2007();
$reader->setReadDataOnly($readDataOnly);
if ($reader->canRead($fileName)) return $reader;
}
// Note that csv does not actually check for a csv file
$reader = new \PHPExcel_Reader_CSV();
if ($reader->canRead($fileName)) return $reader;
throw new Exception("No Reader found for $fileName");
}
public function load($fileName, $readDataOnly = true)
{
$reader = $this->createReaderForFile($fileName,$readDataOnly);
return $reader->load($fileName);
}
}
Now in your code you would have something like:
$excel = new Excel();
$reader = $excel->load('SomeFileName.xls');
$ws = $reader->getSheet(0);
$rows = $ws->toArray();
And process away.

the example of Cerad is an option but it doesn't use that bundle and neither work with mysql,
that bundle is a simple dependency that expose services,
If you have to store data from excel to mysql,
you need first do upload file somewhere, then
read the file with the service,
$excelObj = $this->get('xls.load_xls5')->load($filename);
and then you have to read the documentation of PHPExcel
Hope it helps a little

Related

Attachments Overrides existing while adding from VendorMaint graph

I am importing data and documents from third party application into Acumatica.
After importing, I am creating Vendor dynamically using below code along with attachments.
VendorMaint graph = PXGraph.CreateInstance<VendorMaint>();
VendorR row1 = null;
row1 = new VendorR();
row1.AcctName = VendorName;
row1.NoteID = noteid; // Existing - GUID created while importing
graph.BAccount.Update(row1);
If attachment already exists then it should update instead of duplicating.
In this case if Vendor already exists with files attached, then my code overrides these attachments and remove all previous files attached to that existing vendor.
I want to add the attachment instead of override the existing attachment. Any suggestion?
Try to use insert method of view:
VendorMaint graph = PXGraph.CreateInstance<VendorMaint>();
var row1 = new VendorR();
row1 = graph.BAccount.Insert(row1);
if (row1 == null) // already inserted or wasn't able to insert
{
//some logic with newly created vendor
}
else
{
//some logic with existed
}
row1.AcctName = "vendor name";
row1.NoteID = noteid; // Existing - GUID created while importing
graph.BAccount.Update(row1);
I have found the solution for the issue. Below code helps to create a new attachment and does not override any existing attachments for an existing Vendor.
// Getting the FileID of the attached file from DACClass
UploadFile uf = PXSelectJoin<UploadFile,
InnerJoin<NoteDoc, On<NoteDoc.fileID, Equal<UploadFile.fileID>>,
InnerJoin<DACClass, On<DACClass.noteID, Equal<NoteDoc.noteID>>>>,
Where<DACClass.noteID, Equal<Required<DACClass.noteID>>>>.Select(this, noteid);
if (uf != null)
{
PXNoteAttribute.SetFileNotes(graph.BAccount.Cache, graph.BAccount.Current, uf.FileID.Value);
NoteDoc doc = new NoteDoc();
doc.NoteID = uf.FileID.Value;
doc.FileID = new Guid();
graph.BAccount.Cache.Insert(doc);
}

Read Excel 2007 Workbook Custom Properties without opening or running macros

I'm writing a program (in C#) that will be able to replace a local workbook from a server if the server version is higher, and then open it. To this end I'm trying to read Custom Property "Revision Number" of both local and server copies. The issue is that the workbook contains macros that launch on open, and I don't want to run any macros just to check the Revision Code. So is there a way to read the Revision Number of an excel 2007 xlsm file without actually opening it? If not, is there a way to open a workbook in C# and not execute it's macros?
Actually I tried the tkacprow's suggestion to use OpenXML and it worked. It just took me a while to produce a working code and I just got it working yesterday. Fratyx, your tip also looks interesting - i'll keep that in mind. Here's a working code:
public string GetVersion(string fileName)
{
string propertyValue = string.Empty;
try
{
using (var wb = SpreadsheetDocument.Open(fileName, false))
{
const string corePropertiesSchema = "http://schemas.openxmlformats.org/package/2006/metadata/core-properties";
const string dcPropertiesSchema = "http://purl.org/dc/elements/1.1/";
const string dcTermsPropertiesSchema = "http://purl.org/dc/terms/";
// Get the core properties part (core.xml).
CoreFilePropertiesPart xCoreFilePropertiesPart;
xCoreFilePropertiesPart = wb.CoreFilePropertiesPart;
// Manage namespaces to perform XML XPath queries.
NameTable nt = new NameTable();
XmlNamespaceManager nsManager = new XmlNamespaceManager(nt);
nsManager.AddNamespace("cp", corePropertiesSchema);
nsManager.AddNamespace("dc", dcPropertiesSchema);
nsManager.AddNamespace("dcterms", dcTermsPropertiesSchema);
// Get the properties from the package.
XmlDocument xdoc = new XmlDocument(nt);
// Load the XML in the part into an XmlDocument instance.
xdoc.Load(xCoreFilePropertiesPart.GetStream());
string searchString = string.Format("//cp:coreProperties/{0}", "cp:version");
XmlNode xNode = xdoc.SelectSingleNode(searchString, nsManager);
if (!(xNode == null))
{
//Console.WriteLine(" version is " + xNode.InnerText);
propertyValue = xNode.InnerText;
}
}
}
catch (OpenXmlPackageException e)
{
throw new ApplicationException(String.Format("Incorrect Format detected in a file: {0}" , fileName),e.GetBaseException());
}
return propertyValue;
}

Exception when open excel: File contains corrupted data

I am trying to read an excel with OpenXML.
What I did is simply as following:
private WorkbookPart wbPart = null;
private SpreadsheetDocument document = null;
public byte[] GetExcelReport()
{
byte[] original = File.ReadAllBytes(this.originalFilename);
using (MemoryStream stream = new MemoryStream())
{
stream.Write(original, 0, original.Length);
using (SpreadsheetDocument excel = SpreadsheetDocument.Open(stream, true))
{
this.document = excel;
this.wbPart = document.WorkbookPart;
UpdateValue();
}
stream.Seek(0, SeekOrigin.Begin);
byte[] data = stream.ToArray();
return data;
}
}
I initialized this.originalFilename in the constructor. It is the filename ended with '.xlsx' which i created with excel 2010.
But this line of code
using (SpreadsheetDocument excel = SpreadsheetDocument.Open(stream, true))
gives the exception: Message: System.IO.FileFormatException: File contains corrupted data.
The StackTrace:
Does anyone know how to solve this problem? At the beginning, I didn't use the Stream, I just use SpreadsheetDocument.Open(filename, true). However, it turns out to be exactly the same exception.
I've tried to create a new .xlsx file, but it's still the same.
There is a MSDN page which describes the process of reading and writing Excel file using stream and open xml SDK.
http://msdn.microsoft.com/en-us/library/office/ff478410.aspx
Try extracting the document contents through zip application and check whether you are getting the standard folders inside like xl,docProps and _rels etc.,
This is a method to find whether the package is properly packaged as archive or not.
Hope this helps.

Excel File Password Protection with Open XML SDK

I am using Open XML SDK for creating excel files.
I want to protect them with a password.
Do you know anyway to protect excel file with a password by using Open XML SDK?
I know "com" object way to protect them however, it is not suitable for my application. I need to protect file by using Open XML SDK or another way.
Creating an excel password for protecting workbook or worksheet is possible by open xml.
Following code samples are suggestions of Vincent (http://spreadsheetlight.com/about/) (https://stackoverflow.com/users/12984/vincent-tan) (again I thank him a lot :)
using (SpreadsheetDocument spreadSheet = SpreadsheetDocument.Open(docname,true))
{
foreach (var worksheet in spreadSheet.WorkbookPart.WorksheetParts)
{
worksheet.Worksheet.Append(new SheetProtection(){ Password = “CC”});
// add this in case it still doesn’t work. This makes sure the data is saved.
//worksheet.Worksheet.Save();
}
}
If you have a chart or something then
Following code samples are suggestions of Vincent (http://spreadsheetlight.com/about/) (https://stackoverflow.com/users/12984/vincent-tan) (again I thank him a lot :)
bool bFound;
OpenXmlElement oxe;
SheetProtection prot;
using (SpreadsheetDocument spreadSheet = SpreadsheetDocument.Open("OtoPark.xlsx", true))
{
foreach (var worksheet in spreadSheet.WorkbookPart.WorksheetParts)
{
prot = new SheetProtection();
prot.Password = "CC";
// these are the "default" Excel settings when you do a normal protect
prot.Sheet = true;
prot.Objects = true;
prot.Scenarios = true;
// Open up Excel and do a password protect yourself and use the
// Productivity Tool to see the property values of the resulting Excel file.
// Consider not using the Password property and use:
//prot.AlgorithmName = "SHA-512";
//prot.HashValue = "somehashvaluebythealgorithm";
//prot.SaltValue = "somesalt";
//prot.SpinCount = 100000;
bFound = false;
oxe = worksheet.Worksheet.FirstChild;
foreach (var child in worksheet.Worksheet.ChildElements)
{
// start with SheetData because it's a required child element
if (child is SheetData || child is SheetCalculationProperties)
{
oxe = child;
bFound = true;
}
}
if (bFound)
{
worksheet.Worksheet.InsertAfter(prot, oxe);
}
else
{
worksheet.Worksheet.PrependChild(prot);
}
worksheet.Worksheet.Save();
}
}
These methods makes a protection that any user cant change the data accidentally. However, if you do not want any user that don't know password to see the data then you can use following library:
http://dotnetzip.codeplex.com/
You have a password protected zipped file that contains your excel.xlsx file by using the dotnetzip library.
An example:
public void RNCreateZipFile(string ExcelDocName,string PassWord, string ZipDocName)
{
// create a zip
using (var zip = new ZipFile())
{
zip.Password = PassWord;
zip.AddFile(ExcelDocName, "");
zip.Save(ZipDocName);
}
}
As #Birol mentioned that it will only protect (or rather lock) WB or WS but user can still open file in read only mode. Using dotnetzip package, it will password protect the files inside zip but it will allow the user to see the file second time without asking for password as it is the default windows behavior. You can use free Spire.XLS which will prompt you to enter password to open it any time. It has some limitations though. You can refer - https://www.nuget.org/packages/FreeSpire.XLS/

Creating Sharepoint Directory Recurisvely

I am attempting to create a set of folders that comes in from a flat file in the manner of.
X/Y/Z
and I would like to create a directory for each of these but my memory of recursion has got me in knotts.
here is my code can someone advise.
public void CreateDirectory(SPFolderCollection oWeb, string folder)
{
SPFolder theFolder = oWeb.Add(folder);
theFolder.Update();
}
public void FolderCreator(SPWeb oWeb)
{
StreamReader reader = new StreamReader(this.txtFolders.Text);
while (reader.Peek() != -1)
{
string folderLine = reader.ReadLine();
if (folderLine.Contains("/"))
{
SPFolderCollection collection = oWeb.Folders["Documents"].SubFolders[folderLine.Split('/')[0]].SubFolders;
CreateDirectory(collection, folderLine);
}
SPFolderCollection newCollection = oWeb.Folders["Documents"].SubFolders;
CreateDirectory(newCollection, folderLine);
}
}
This does not work I am looking for it to do recrusion so if I pass
ABC/DEF/GHI
and
ABC/DEF
it will go and create the folders appropriately.
But I am stuck as how to do that.
The SPFileCollection.Add() methods allow you to pass in the full relative path of a file. So this may be an option assuming you aren't just generating a folder structure, which you may be doing, in which case this won't really work unless you create a temporary file and then delete it to keep the folder path.
web.Files.Add("/sites/somesite/shared documents/foldera/folderb/folderc/somefile.txt", stream);

Resources