displaying the mismatch into the excel using php - excel

I am importing the the csv data into the database, records which are not matching with the dtdc are the mismatch are mismatched records . I am exporting those records into excel.Below is the else condition which we are taking the mismatch records
else{
$mismarchrows_dtdc[] = $row['Postcode'];
$mismatchcount_dtdc = $mismatchcount_dtdc+1;
}
Here i am writing the mismatched records into excel
$fileName_dtdc = 'uploads/csv/already_exist_customer_dtdc-'.time().'.xls';
$fp = fopen($fileName_dtdc, 'w');
$newLineSeparator = "\r\n";
$line1_dtdc = 'postcode'.$newLineSeparator;
fwrite($fp,$line1_dtdc);
foreach($mismarchrows_dtdc as $mrow){
$line2_dtdc = $mrow;
fwrite($fp,$line2_dtdc);
}
now only one column called postcode is only exported into excel, but i 5 more columns like firstname,lastname,middlename in to the excel with data
I tried by keeping like this, But coming in only one column
else{
$mismarchrows_dtdc[] = $row['Postcode'];
$mismarchrows_dtdc1[] .= $row['State'];
$mismatchcount_dtdc = $mismatchcount_dtdc + 1;
}
can anyone help with this !!!!!!!!!!!!!!!!!

I don't know your exact needs, but maybe this will help?
$csv_lines = array();
foreach($mismarchrows_dtdc as $mrow) {
$keys = array_keys($mrow);
$data = array();
foreach ($keys as $key) {
$data[] = $mrow[$key];
}
$csv_lines[] = implode(',',$data);
}
$fileName_dtdc = 'uploads/csv/already_exist_customer_dtdc-'.time().'.xls';
file_put_contents($fileName_dtdc,implode("\r\n",$csv_lines));

Related

EPPlus corrupt Excel file when having more than 65,530 rows

I'm running into an issue with EPPlus when there are more than 65,530 rows that have a column with a hyperlink. The example below is configured to create 65,530 rows. With this number it will create the Excel file correctly (not corrupt). Once you run it with anything over 65,530, the Excel file will be created but when you open it, Excel will report that is corrupt. Any ideas how to solve this issue?
try
{
int maxRowsToCreate = 65530; //-- no errors will be generated
//int maxRowsToCreate = 65531; //-- error will be generated. The Excel file will be created but will give an error when trying to open it.
string report = string.Format("D:\\temp\\hypelinkIssue-{0}.xlsx", maxRowsToCreate.ToString());
if (File.Exists(report))
{
File.Delete(report);
}
using (ExcelPackage pck = new ExcelPackage(new System.IO.FileInfo(report)))
{
//Add the Content sheet
var ws = pck.Workbook.Worksheets.Add("Catalog");
ws.View.ShowGridLines = true;
var namedStyle = pck.Workbook.Styles.CreateNamedStyle("HyperLink"); //This one is language dependent
namedStyle.Style.Font.UnderLine = true;
namedStyle.Style.Font.Color.SetColor(Color.Blue);
ws.Column(1).Width = 100;
int rowIndex = 0;
for (int i = 0; i < maxRowsToCreate; i++)
{
rowIndex += 1;
string fullFilePath = string.Format("D:\\temp\\{0}", Path.GetRandomFileName());
ws.Cells[rowIndex, 1].StyleName = "HyperLink";
ws.Cells[rowIndex, 1].Hyperlink = new Uri(string.Format(#"file:///{0}", fullFilePath));
ws.Cells[rowIndex, 1].Value = fullFilePath;
}
pck.Save();
}
System.Diagnostics.Process.Start(report);
}
catch (Exception ex)
{
throw ex;
}
The issue occurs when using ".Hyperlink". If instead I use ".Formula" and populate it with the "=HYPERLINK" Excel formula, it works fine. I was able to create 250k records with unique hyperlink using this approach. I did not try more than 250k but hopefully it will work fine.
Thanks for pointing me in the right direction.
/*
This only works with LESS than 65,530 hyperlinks
*/
ws.Cells[rowIndex, 1].StyleName = "HyperLink";
ws.Cells[rowIndex, 1].Hyperlink = new OfficeOpenXml.ExcelHyperLink(fullFilePath, ExcelHyperLink.UriSchemeFile);
ws.Cells[rowIndex, 1].Value = fullFilePath;
/*
This works with more that 65,530 hyperlinks
*/
string cellFormula = string.Format("=HYPERLINK(\"{0}\")", filePath);
ws.Cells[rowIndex, 1].Formula = cellFormula;
This is because Excel limits the amount of unique URLs in a file to 65,530. You should try to insert them as text, instead of a url.
For a possible solution, take a look at this answer.

How to include a for and multidimensional array in the body of php mailer?

I am using PHP Mailer.
I want to add dynamic content in php to the body but I am not being able to do it.
If I add this on the php mailer body, it works.
$mail->Body="<h3>Dados do 1º Titular</h3><ul><li><b>Nome: </b>".$titular1_name."</li><li><b>Idade: </b>".$titular1_idade."</li><li><b>Estado Civil</b>".$titular1_estado_civil."</li><li><b>Dependentes</b>".$titular1_dependentes."</li><li><b>Rendimento</b>".$titular1_rendimento."</li><li><b>Penhora</b>".$titular1_penhora."</li></ul><h3>Dados do 2º titular</h3><ul><li><b>Nome: </b>".$titular2_name."</li><li><b>Idade: </b>".$titular2_idade."</li><li><b>Estado Civil</b>".$titular2_estado_civil."</li><li><b>Dependentes</b>".$titular2_dependentes."</li><li><b>Rendimento</b>".$titular2_rendimento."</li><li><b>Penhora</b>".$titular2_penhora."</li></ul><h3>Dados de Contacto</h3><ul><li><b>Email: </b>".$titular_email."</li><li><b>Telefone</b>".$titular_phone."</li><li><b>Localidade</b>".$titular_local."</li></ul>";
But I need to add this result:
for ($y = 0; $y <= $numberOfRows; $y++){
for ($x = 0; $x < $maxData; $x++) {
array_push($row, $credito,
$capital_divida, $prestacao,
$bank, $garantias, $situacao);
echo $row[$x]."<br>";
}
array_push($fullData, $row);
}
This is my relevant code for this issue:
$row = array();
$fullData = array();
$maxData = 6;
$numberOfRows = htmlspecialchars(["numberOfRowsHTML"]);
$titular_email = htmlspecialchars($_POST["titular-email"]);
$titular_phone = htmlspecialchars($_POST["titular-phone"]);
$titular_local = htmlspecialchars($_POST["titular-local"]);
$titular_message = htmlspecialchars($_POST["titular-message"]);
$numberOfRows = htmlspecialchars(["numberOfRowsHTML"]);
$credito = htmlspecialchars(["credito"]);
$capital_divida = htmlspecialchars(["capital_div"]);
$prestacao = htmlspecialchars(["prestacao"]);
$bank = htmlspecialchars(["bank"]);
$garantias = htmlspecialchars(["garantias"]);
$situacao = htmlspecialchars(["situacao"]);
Thank you in advance for all the help
This code doesn't make any sense:
$numberOfRows = htmlspecialchars(["numberOfRowsHTML"]);
It looks like you're missing the name of an array you want to get this value from, for example:
$numberOfRows = htmlspecialchars($_POST["numberOfRowsHTML"]);
Your loop that assembles the array doesn't appear to do anything useful at all - you're getting values from the submission, then assembling an array which you don't use. It would be helpful if you could clarify what it is you're trying to do.

How can I change the format of the ColumnField column headings in EPPlus?

I create a column field in EPPlus like so:
// Column field[s]
var monthYrColField = pivotTable.Fields["MonthYr"];
pivotTable.ColumnFields.Add(monthYrColField);
...that displays like so (the "201509" and "201510" columns):
I want those values to display instead as "Sep 15" and "Oct 15"
In Excel Interop it's done like this:
var monthField = pvt.PivotFields("MonthYr");
monthField.Orientation = XlPivotFieldOrientation.xlColumnField;
monthField.NumberFormat = "MMM yy";
...but in EPPlus the corresponding variable (monthYrColField) has no "NumberFormat" (or "Style") member.
I tried this:
pivotTableWorksheet.Column(2).Style.Numberformat.Format = "MMM yy";
...but, while it didn't complain or wreak havoc, also did not change the vals from "201509" and "201510"
How can I change the format of my ColumnField column headings in EPPlus from "untransformed" to "MMM yy" format?
UPDATE
For VDWWD:
As you can see by the comments, there are many things related to PivotTables which don't work or are hard to get to work in EPPlus; Excel Interop is a bear (and not a teddy or a Koala, but more like a grizzly) compared to EPPlus, but as to PivotTables, it seems that EPPlus is kind of half-baked to compared to Exterop's fried-to-a-crispness.
private void PopulatePivotTableSheet()
{
string NORTHWEST_CORNER_OF_PIVOT_TABLE = "A6";
AddPrePivotTableDataToPivotTableSheet();
var dataRange = pivotDataWorksheet.Cells[pivotDataWorksheet.Dimension.Address];
dataRange.AutoFitColumns();
var pivotTable = pivotTableWorksheet.PivotTables.Add(
pivotTableWorksheet.Cells[NORTHWEST_CORNER_OF_PIVOT_TABLE],
dataRange,
"PivotTable");
pivotTable.MultipleFieldFilters = true;
pivotTable.GridDropZones = false;
pivotTable.Outline = false;
pivotTable.OutlineData = false;
pivotTable.ShowError = true;
pivotTable.ErrorCaption = "[error]";
pivotTable.ShowHeaders = true;
pivotTable.UseAutoFormatting = true;
pivotTable.ApplyWidthHeightFormats = true;
pivotTable.ShowDrill = true;
// Row field[s]
var descRowField = pivotTable.Fields["Description"];
pivotTable.RowFields.Add(descRowField);
// Column field[s]
var monthYrColField = pivotTable.Fields["MonthYr"];
pivotTable.ColumnFields.Add(monthYrColField);
// Data field[s]
var totQtyField = pivotTable.Fields["TotalQty"];
pivotTable.DataFields.Add(totQtyField);
var totPriceField = pivotTable.Fields["TotalPrice"];
pivotTable.DataFields.Add(totPriceField);
// Don't know how to calc these vals here, so had to put them on the data sheet
var avgPriceField = pivotTable.Fields["AvgPrice"];
pivotTable.DataFields.Add(avgPriceField);
var prcntgOfTotalField = pivotTable.Fields["PrcntgOfTotal"];
pivotTable.DataFields.Add(prcntgOfTotalField);
// TODO: Get the sorting (by sales, descending) working:
// These two lines don't seem that they would do so, but they do result in the items
// being sorted by (grand) total purchases descending
//var fld = ((PivotField)pvt.PivotFields("Description"));
//fld.AutoSort(2, "Total Purchases");
//int dataCnt = pivotTable.ra //DataBodyRange.Columns.Count + 1;
FormatPivotTable();
}
private void FormatPivotTable()
{
int HEADER_ROW = 7;
if (DateTimeFormatInfo.CurrentInfo != null)
pivotTableWorksheet.Column(2).Style.Numberformat.Format =
DateTimeFormatInfo.CurrentInfo.YearMonthPattern;
// Pivot Table Header Row - bold and increase height
using (var headerRowFirstCell = pivotTableWorksheet.Cells[HEADER_ROW, 1])
{
headerRowFirstCell.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
headerRowFirstCell.Style.Font.Bold = true;
headerRowFirstCell.Style.Font.Size = 12;
pivotTableWorksheet.Row(HEADER_ROW).Height = 25;
}
ColorizeContractItemBlocks(contractItemDescs);
// TODO: Why is the hiding not working?
HideItemsWithFewerThan1PercentOfSales();
}
You can use the build-in Date format YearMonthPattern. which would give september 2016 as format.
pivotTableWorksheet.Column(2).Style.Numberformat.Format = DateTimeFormatInfo.CurrentInfo.YearMonthPattern;
If you really want MMM yy as pattern, you need to overwrite the culture format:
Thread.CurrentThread.CurrentCulture = new CultureInfo("nl-NL")
{
DateTimeFormat = { YearMonthPattern = "MMM yy" }
};
pivotTableWorksheet.Column(2).Style.Numberformat.Format = DateTimeFormatInfo.CurrentInfo.YearMonthPattern;
It doesn't seem that you can set the format on the field itself. You have to access through the pivot table object:
pivotTable.DataFields[0].Format = "MMM yy";
Any formatting applied to the underlying worksheet seems to be completely ignored.

File error on opening spreadsheet created with Spreadsheet::WriteExcel

I was using Spreadsheet::WriteExcel to create xls file using perl. When the range of spreadsheet increased, the Microsoft excel shows an alert before opening the file "File Error: Data may have been lost".
Please help me to solve this.
Here is the code
my $row = 2;
foreach my $sid(array of students objects)
{
my $s = $students->{$sid};
my $cc = 0;
my $wall = f1($x, $y, $z);#f1 is a method returns hash of arrays that have to write on excel having keys #key_array
foreach my $key (#key_array) {
my $t_row = $row;
my $i_c = 0;
my $t_col = 0;
my $m_row = $max_row;
while($m_row > 0){
$t_col = 3+($cc*7);
if($cc == 0){
$ws->write($t_row, 0,
[$s->{first_name}, $s->{last_name}, $s->{l_name}], $fmt_wrap
);
}
if(defined $wall->{$key}->[$i_c] ){
$ws->write($t_row, $t_col, $wall->{$key}->[$i_c], $fmt_wrap);
} else {
$ws->write($t_row, (3+$cc*7),["","","","","","",""], $fmt_wrap);
}
$t_row++;
$i_c++;
$m_row--;
}#while loop
$ws->write($t_row-1, 3+$company_format*$max_step,
[ (scalar keys %{$s->{videos}}), $s->{total_pageviews} ], $fmt
);
$cc++;
$t_row = 2;
}#foreach loop
$row+=$max_row;
}#foreach student array
I have found answer. In the code there was a line which write data into a cell multiple times. So i found that multiple write attempt to a particular cell can cause file corruption.

search for a cell from one excel and search in another excel and print if its not there using perl

I'm new to perl. I have two excel files containing huge no of rows and just two columns. I want to get each cell from one of the excel files and search whether its there in another excel file or not. if its not then print that cell.
I believe that if I get each cell from one of the excel and search it in another and then run a for loop for all the rows it will be done.
I reached upto getting the cell from first excel but how to search whether it is there in the another excel and printing it is the issue.
can anybody help. ??
I'm not entirely sure what you want, but this might give you some ideas. It's completely untested, though.
use strict;
use Spreadsheet::ParseExcel;
my $parser = Spreadsheet::ParseExcel->new();
my $workbook1 = $parser->parse('Book1.xls');
if (!defined $workbook1) { die $parser->error(), ".\n"; }
my $workbook2 = $parser->parse('Book2.xls');
if (!defined $workbook2) { die $parser->error(), ".\n"; }
$worksheet1 = $workbook1->worksheet('Sheet1');
$worksheet2 = $workbook2->worksheet('Sheet1');
my ($row_min1, $row_max1) = $worksheet1->row_range();
my ($col_min1, $col_max1) = $worksheet1->col_range();
for my $row1 ($row_min1 .. $row_max1) {
for my $col1 ($col_min1 .. $col_max1) {
my $cell1 = $worksheet1->get_cell($row1, $col1);
my ($row_min2, $row_max2) = $worksheet2->row_range();
my ($col_min2, $col_max2) = $worksheet2->col_range();
my $found_match = 0;
for my $row2 ($row_min2 .. $row_max2) {
for my $col2 ($col_min2 .. $col_max2) {
my $cell2 = $worksheet2->get_cell($row2, $col2);
if ($cell1->value() eq $cell2->value()) { # or == ?
$found_match = 1;
break;
}
}
break if $found_match;
}
if (!$found_match) {
print $cell1->value, "\n";
}
}
}
This is mostly from here: http://search.cpan.org/dist/Spreadsheet-ParseExcel/lib/Spreadsheet/ParseExcel.pm

Resources