I am using Openxmlto write to excel uisng C#
It is writing in excel but if data exceeds textbox length, it is not wrapping up and coming to second line. Attaching screenshot for same.
How to wrap the same ?
ExcelOxml.SetCellValue(document, worksheet1, 5, 89, pricingmodel.PricingDetailExtended.PricingProductDetail.OpportunityId, false);
Please use the below code to wrap the text in excel
//Create a cell format
CellFormat cellformat1 = new CellFormat(new Alignment() { WrapText=true});
CellFormats cellformats = new CellFormats();
cellformats.Append(cellformat1);
workbookstylesheet.Append(cellformats);
stylesheet.Stylesheet = workbookstylesheet;
stylesheet.Stylesheet.Save();
Related
I got the Excel file from file-picker as Uint8list, and convert to it File now:
FilePickerResult result = await FilePicker.platform.pickFiles( type: FileType.custom, allowedExtensions: ['xlsx'], );
if (result != null)
{ var file = File.fromRawPath(result.files.single.bytes);
}
How I convert it to a Syncfusion XLSIO workbook (fromUint8list or File) for reading data from sheet 0 ? Thanks.
Currently, we don't have support to read Excel using Flutter XlsIO library.
However, you can create Excel files using "syncfusion_flutter_xlsio" library with the following features.
Create a simple Excel document
Add text, number, and datetime values
Add formulas
Apply formatting
Add images
Add charts
Add hyperlinks to texts and images
Protect workbooks and worksheets
AutoFit rows and columns
Insert or delete rows and columns
Apply conditional formatting
To know more about the "syncfusion_flutter_xlsio" library please refer the following link.
https://pub.dev/packages/syncfusion_flutter_xlsio
I have a problem with my code. I generate an excel file unsing PhpSpreadsheet lib. So i can write my data and it worked fine. I add a data validation list in a cell using an other worksheet and it work too. So I try to add in a cell a formula which can change the value (using VLOOKUP) when someone select something in my data validation list and this work too.
But my problem is my formula is not calculated when I open my file. When I open the file I just see the formula and I wanted to see the result.
This is my code:
$i=2;
$j=6;
$filename = "export-excel.xlsx";
$spreadsheet = new Spreadsheet();
$dataSheet = $spreadsheet->getSheet(0);
$dataSheet1 = $spreadsheet->createSheet(1);
$dataSheet1->setTitle("Materiel");
$dataSheet1->setCellValue('A1','Modèle');
$dataSheet1->setCellValue('B1','Marque');
$dataSheet1->setCellValue('C1','Calibre');
$dataSheet1->setCellValue('D1','ITH');
$dataSheet1->setCellValue('E1','IMG');
$dataSheet1->setCellValue('F1','Type Matériel');
//remplissage matériel
$listMateriel = $this->entityManager->getRepository(Materiel::class)->findAll();
$nbrMateriel = count($listMateriel) +1;
foreach($listMateriel as $materiel){
$dataSheet1->setCellValue('A'.$i,$materiel->getModele());
$dataSheet1->setCellValue('B'.$i,$materiel->getMarque());
$dataSheet1->setCellValue('C'.$i,$materiel->getCalibre());
$dataSheet1->setCellValue('D'.$i,$materiel->getIth());
$dataSheet1->setCellValue('E'.$i,$materiel->getImg());
$dataSheet1->setCellValue('F'.$i,$materiel->getTypeMateriel()->getLibelle());
$i++;
}
//remplissage enveloppe
$enveloppe = $appareil->getEnveloppe();
$dataSheet->setCellValue('A5',1);
$dataSheet->setCellValue('B5',1);
$dataSheet->setCellValue('C5',$enveloppe->getLieu()->getLibelle());
$dataSheet->setCellValue('D5',$enveloppe->getNom());
$dataSheet->setCellValue('E5',$enveloppe->getNumeroschema());
$dataSheet->setCellValue('F5',$enveloppe->getCodegmao());
$dataSheet->setCellValue('G5',$enveloppe->getCodemire());
$dataSheet->setCellValue('H5',$enveloppe->getIk());
$dataSheet->setCellValue('I5',$enveloppe->getResponsable());
$dataSheet->setCellValue('J5',$enveloppe->getUnitegeo());
$dataSheet->setCellValue('K5',$enveloppe->getCentreMainteneur());
//remplissage appareil
foreach($enveloppe->getAppareils() as $app){
$dataSheet->setCellValue('A'.$j,1);
$dataSheet->setCellValue('B'.$j,2);
$dataSheet->setCellValue('C'.$j,$app->getRepere());
$dataSheet->setCellValue('D'.$j,$app->getNom());
$dataSheet->setCellValue('E'.$j,$app->getOrdreDansArmoire());
$dataSheet->setCellValue('F'.$j,$app->getMonotri());
$dataSheet->setCellValue('G'.$j,$app->getDepart());
$dataSheet->setCellValue('H'.$j,$app->getDdr());
$dataSheet->setCellValue('I'.$j,$app->getCalibreddr());
$dataSheet->setCellValue('J'.$j,$app->getMotorise());
$dataSheet->setCellValue('K'.$j,$app->getAlarme());
$dataSheet->setCellValue('L'.$j,(null === $app->getNaturealimentation()) ? '' : $app->getNaturealimentation()->getLibLong());
$dataSheet->setCellValue('M'.$j,$app->getSimultaneite());
$dataSheet->setCellValue('N'.$j,$app->getCompteur());
$dataSheet->setCellValue('O'.$j,(null === $app->getTypeconsommateur()) ? '' : $app->getTypeconsommateur()->getLibelle());
$dataSheet->setCellValue('P'.$j,$app->getTypecable());
$dataSheet->setCellValue('Q'.$j,$app->getNumcable());
$dataSheet->setCellValue('R'.$j,$app->getLongueurcable());
$dataSheet->setCellValue('S'.$j,$app->getSectioncable());
$dataSheet->setCellValue('T'.$j,$app->getMateriel()->getModele());
$this->dataValidation('T'.$j, $spreadsheet, $nbrMateriel);
$dataSheet->setCellValue('U'.$j,$app->getReglageIth());
$dataSheet->setCellValue('V'.$j,$app->getReglageImag());
$dataSheet->setCellValue('W'.$j,$app->getObservation());
//This is my formula who work fine
$dataSheet->setCellValueExplicit('X'.$j,'=SI(T'.$j.'<>"";RECHERCHEV(T'.$j.';Materiel!$A$2:$F$'.$nbrMateriel.';4;FAUX);"SO")', \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING);
$spreadsheet->getActiveSheet()->getCell('X'.$j)->getCalculatedValue();
Calculation::getInstance($spreadsheet)->disableCalculationCache();
$dataSheet->setCellValue('Y'.$j,$app->getMateriel()->getImg());
$j++;
}
$tmpPath = $this->getTmpFile2();
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->setPreCalculateFormulas(true);
$writer->save($tmpPath);
This is what I have when I open my file:
I want to keep my formula in the cell and just show the result when I open my file. So someone have an Idea to how I can calculate my formula before to open my file ? I try with the documentation but it doesn't work.
Than in advance
The problem is that you use \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING in
$dataSheet->setCellValueExplicit('X'.$j,'=SI(T'.$j.'<>"";RECHERCHEV(T'.$j.';
Materiel!$A$2:$F$'.$nbrMateriel.';4;FAUX);"SO")', \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING);
you should use TYPE_FORMULA.
A other common problem for non calculate are string operants instead of number typ operants in the formula. If you have string typs as operant the calculation excel refuse executed by opening the formula.
i am having difficulties with open xml sdk:
i am trying to generate excel file with several columns that have numbers and i want to have total sum at the end
i have tried to Generate Table Definition Part Content and inside define every column (id, name etC). If column has true for TotalColumn, it adds code (rough example)
var column = new TableColumn{
id = 1,
name = "example",
TotalsRowFunction = TotalsRowFunctionValues.Sum,
TotalsRowFormula = new TotalsRowFormula("=SUBTOTAL(109;[" + rowName + "])")
};
I can't get it to work, when i open excel it reports error, but it doesn't explicitly says what the problem is... I tried with microsoft validator but can't figure anything out...
I'd appreciate any help / example code since i can't google anything out
EDIT:
i use this at the end:
workbookPart.Workbook.CalculationProperties.ForceFullCalculation = true;
workbookPart.Workbook.CalculationProperties.FullCalculationOnLoad = true;
Why not use a cell formula?
E.g.
cell.DataType = new EnumValue<CellValues>(CellValues.Number);
cell.CellFormula = new CellFormula(string.Format("=SUBTOTAL({0};[{1}])", "109", rowName));
//This will force a full recalculation of all the cells
workbookPart.Workbook.CalculationProperties.ForceFullCalculation = true;
workbookPart.Workbook.CalculationProperties.FullCalculationOnLoad = true;
I ended using EPPlus for this as it seems to be working simple and efficient
In my rdlc report have following columns
SlNo, Item, Uom, Qty, Rate, Amount
Here the Amount field is a formula (Rate*Qty)
The report is working fine, and when i export to excel also displaying the values are correctly.
But my problem is, after export to excel, when i change the Qty or Rate columns in excel file the Amount is not get changed automatically, because the formula is missing in the excel cell.
How can we include the formula in Amount column while export to excel from .rdlc?
I'm afraid that this required behaviour isn't really possible by just using the rdlc rendering.
In my search I stumbled upon this same link that QHarr posted: https://social.msdn.microsoft.com/Forums/en-US/3ddf11bf-e10f-4a3e-bd6a-d666eacb5ce4/report-viewer-export-ms-report-data-to-excel-with-formula?forum=vsreportcontrols
I haven't tried the project that they're suggesting but this might possibly be your best solution if it works. Unfortunately I do not have the time to test it myself, so if you test this please share your results.
I thought of the following workaround that seems to work most of the times, but isn't really that reliable because the formula sometimes gets displayed as full-text instead of being calculated. But I guess this could be solved by editing the excel file just after being exported, and changing the cell properties of this column containing the formula or just triggering the calculate.
Using the built-in-field Globals!RenderFormat.Name you can determine the render mode, this way you can display the result correctly when the report is being rendered to something different than Excel. When you export to Excel, you could change the value of the cell to the actual formula.
To form the formula it's self you'll need to figure this out on your own, but the RowNumber(Scope as String) function can be of use here to determine the row number of your cells.
Here is a possible example for the expression value of your amount column
=IIF(Globals!RenderFormat.Name LIKE "EXCEL*", "=E" & Cstr(RowNumber("DataSet1")+2) & "*F" & Cstr(RowNumber("DataSet1")+2) ,Fields!Rate.Value * Fields!Qty.Value )
Now considering that this formula sometimes gets displayed as full-text, and you'll probably have to edit the file post-rendering. If it's too complicated to determine which row/column the cell is on, you could also do this post-rendering. But I believe that the above expression should be easy enough to use to get your desired result without having to do much after rendering.
Update: The following code could be used to force the calculation of the formula (post rendering)
var fpath = #"C:\MyReport.xlsx";
using (var fs = File.Create(fpath))
{
var lr = new LocalReport();
//Initializing your reporter
lr.ReportEmbeddedResource = "MyReport.rdlc";
//Rendering to excel
var fbytes = lr.Render("Excel");
fs.Write(fbytes, 0, fbytes.Length);
}
var xlApp = new Microsoft.Office.Interop.Excel.Application() { Visible = false };
var wb = xlApp.Workbooks.Open(fpath);
var ws = wb.Worksheets[1];
var range = ws.UsedRange;
foreach (var cell in range.Cells)
{
var cellv = cell.Text as string;
if (!string.IsNullOrWhiteSpace(cellv) && cellv.StartsWith("="))
{
cell.Formula = cellv;
}
}
wb.Save();
wb.Close(0);
xlApp.Quit();
While I'm trying to open excel file a message box is prompting like "We found a problem with some content in file name. Do you want us to try to recover as much as we can? If you trust the source of this workbook, click Yes.". What actually done is i have a excel template designed and copying the file to another file and created temp file I'm inserting data to temp file using OPEN XML and data is getting from the database.
i have tried the solutions provided in the net but those fixes are not resolving my issue.My excel is 2010
Anyone solution provided is much appreciated.
I had this problem. It was caused by the way I was storing numbers and strings in cells.
Numbers can be stored simply using cell.CellValue = new CellValue("5"), but for non-numeric text, you need to insert the string in the SharedStringTable element and get the index of that string. Then change the data type of the cell to SharedString, and set the value of the cell to the index of the string in the SharedStringTable.
// Here is the text I want to add.
string text = "Non-numeric text.";
// Find the SharedStringTable element and append my text to it.
var sharedStringTable = document.WorkbookPart.GetPartsOfType<SharedStringTablePart>().First().SharedStringTable;
var item = sharedStringTable.AppendChild(new SharedStringItem(new Text(text)));
// Set the data type of the cell to SharedString.
cell.DataType = new EnumValue<CellValues>(CellValues.SharedString);
// Set the value of the cell to the index of the SharedStringItem.
cell.CellValue = new CellValue(item.ElementsBefore().Count().ToString());
This is explained in the documentation here: http://msdn.microsoft.com/en-us/library/office/cc861607.aspx
Another few cases that can cause this type of error:
Your sheet name is longer than 31 characters
You have invalid characters in sheet name
You have cells with values longer than 32k
The issue is due to using
package.Save();
and
package.GetAsByteArray();
at the same time
when we call
package.GetAsByteArray();
it will do following operations
this.Workbook.Save();
this._package.Close();
this._package.Save(this._stream);
Hence, removing
package.Save();
will solve this problem "We found a problem with some content in file name. Do you want us to try to recover as much as we can? If you trust the source of this workbook, click Yes."
Another possible cause could be exceeded maximum number of cell styles.
You can define:
up to 4000 styles in a .xls workbook
up to 64000 styles in a .xlsx workbook
In this case you should re-use the same cell style for multiple cells, instead of creating a new cell style for every cell.
I added the right cellReference and fixed this issue for me:
string alpha = "ABCDEFGHIJKLMNOPQRSTUVQXYZ";
for (int colInx = 0; colInx < reader.FieldCount; colInx++)
{
AppendTextCell(alpha[colInx] + "1", reader.GetName(colInx), headerRow);
}
private static void AppendTextCell(string cellReference, string cellStringValue, Row excelRow)
{
// Add a new Excel Cell to our Row
Cell cell = new Cell() { CellReference = cellReference, DataType = new EnumValue<CellValues>(CellValues.String) };
CellValue cellValue = new CellValue();
cellValue.Text = cellStringValue.ToString();
cell.Append(cellValue);
excelRow.Append(cell);
}
Same warning but the problem with me was that I was using a client input (name of wave) as sheet name for the file and when date was presented within the name, the character '/' used as date part separator was causing the issue.
I think Microsoft need to provide a better error log to save people time investigate such minor issues. Hope my answer will save someone else's time.
The issue was due to storing a string in the cell directly using cell.CellValue = new CellValue("Text"). It is possible to store numbers like this but not string. For string, define data type as string before assigning the text using Cell.DataType = CellValues.String;