I have a requirement where excel file ( i will treat this is an a template) which has a pre populated formulas ( for close to 10k rows), when i populate the dependent column values the formulas calculations are not updated or refreshed. please help me with the same.
The formulas will be populated for 10k rows but while populating the data i may be populating the data just for 100 rows but user can add many more records later so we populate the formulas for 10k rows.
Code below:
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using Microsoft.IT.Sales.RelationshipManagement.Segmentation.DataContracts;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
PopulateExcel("E:\\Formula.xlsx");
Console.WriteLine("Hello World!");
}
private static void PopulateExcel(string Path)
{
WorkbookPart WP;
//WorksheetPart WSP;
String rId;
Worksheet WS;
SheetData StD;
Row R1;
Row R2;
Row R3;
Cell C1;
Cell C2;
Cell C3;
CellFormula CF;
CalculationChainPart CP;
CalculationChain CC;
CalculationCell CCell;
Workbook Workbook;
Sheet ss;
Sheet Sheet;
using (SpreadsheetDocument spreadSheet = SpreadsheetDocument.Open(Path, true))
{
// Get the SharedStringTablePart. If it does not exist, create a new one.
WP = spreadSheet.WorkbookPart;
var wsp = spreadSheet.WorkbookPart.WorksheetParts.FirstOrDefault(); //.ElementAt(sheetnumber);
SheetData sheetData = wsp.Worksheet.Descendants<SheetData>().LastOrDefault();
R1 = GetRow(sheetData, 2);
C1 = new Cell();
SetCell(C1, "A1", 1);
sheetData.Append(R1);
R1.Append(C1);
C2 = new Cell();
SetCell(C2, "B1", 2);
R1.Append(C2);
spreadSheet.WorkbookPart.Workbook.CalculationProperties.ForceFullCalculation = true;
spreadSheet.WorkbookPart.Workbook.CalculationProperties.FullCalculationOnLoad = true;
wsp.Worksheet.Save();
// Close the document.
spreadSheet.Close();
}
}
private static Row GetRow(SheetData wsData, UInt32 rowIndex)
{
var row = wsData.Elements<Row>().
Where(r => r.RowIndex.Value == rowIndex).FirstOrDefault();
if (row == null)
{
row = new Row();
row.RowIndex = rowIndex;
wsData.Append(row);
}
return row;
}
private static void SetCell(Cell cell, string Reference, int Value)
{
cell.CellReference = Reference;
cell.DataType = CellValues.Number;
cell.CellValue = new CellValue();
cell.CellValue.Text = Value.ToString();
}
}
}
Please help me with the code.
Related
I am trying to use a CrystalReportViewer control to display a report in a Visual Studio 2012 project. I am providing all information required to connect to the database, including server name, port number, database name, user name and password. When I run the program below, the control shows me a dialog that includes the correct connection string, database name and user, and prompts me for a password, even though I already gave it one. When I give it the correct password, a pop-up appears saying "Log-in failed. Try again." What am I doing wrong?
By the way, there are no subreports in this report. When I ran the program below, I put a breakpoint in the code that processes subreports, and it was never hit.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
using CrystalDecisions.Windows.Forms;
namespace Example
{
public partial class Form1 : Form
{
private string _serverName;
private string _databaseName;
private string _user;
private string _passwd;
private ReportDocument _report;
public Form1()
{
InitializeComponent();
}
private void crystalReportViewer1_Load(object sender, EventArgs e)
{
string reportFile = "C:\\Users\\rdrichardson\\OneDrive - Rad-Con\\CAPS Builds\\trunk\\Debug Crawfordsville\\Reports\\English\\allbases_no_subreports.rpt";
_report = new ReportDocument();
_report.Load(reportFile);
_serverName = "Provider=Provider=PostgreSQL OLE DB Provider;Data Source=localhost;Port=5432timeout=1000;";
// _serverName = "Driver={PostgreSQL};Server=IP address;Port=5432;Database=Algoma;Uid=caps;Pwd=asdlkjqp;";
// _serverName = "Driver={PostgreSQL};Server=IP address;Port=5432;";
_databaseName = "Algoma";
_user = "caps";
_passwd = "asdlkjqp";
LogOnToTables();
crystalReportViewer1.ReportSource = _report;
}
private void LogOnToTables()
{
string location;
ReportObjects crReportObjects;
SubreportObject crSubreportObject;
ReportDocument crSubreportDocument;
Database crDatabase;
Tables crTables;
TableLogOnInfo crTableLogOnInfo;
ConnectionInfo crConnectInfo = new ConnectionInfo();
if (_report == null) return;
// Setup the ODBC/ADO connect string
crConnectInfo.DatabaseName = _databaseName;
crConnectInfo.ServerName = _serverName;
crConnectInfo.Type = ConnectionInfoType.CRQE;
crConnectInfo.UserID = _user;
crConnectInfo.Password = _passwd;
_report.SetDatabaseLogon(_user, _passwd);
_report.DataSourceConnections.Clear();
crDatabase = _report.Database;
crTables = crDatabase.Tables;
//loop through all the tables and pass in the connection info
foreach (Table crTable in crTables)
{
location = crTable.Location;
crTableLogOnInfo = crTable.LogOnInfo;
crTableLogOnInfo.ConnectionInfo = crConnectInfo;
// crTable.LogOnInfo.ConnectionInfo.DatabaseName = string.Empty;
crTable.ApplyLogOnInfo(crTableLogOnInfo);
}
//set the crSections object to the current report's sections
Sections crSections = _report.ReportDefinition.Sections;
//loop through all the sections to find all the report objects
foreach (Section crSection in crSections)
{
crReportObjects = crSection.ReportObjects;
//loop through all the report objects to find all the subreports
foreach (CrystalDecisions.CrystalReports.Engine.ReportObject crReportObject in crReportObjects)
{
if (crReportObject.Kind == ReportObjectKind.SubreportObject)
{
//you will need to typecast the reportobject to a subreport
//object once you find it
crSubreportObject = (SubreportObject)crReportObject;
//open the subreport object
crSubreportDocument = crSubreportObject.OpenSubreport(crSubreportObject.SubreportName);
//set the database and tables objects to work with the subreport
crDatabase = crSubreportDocument.Database;
crTables = crDatabase.Tables;
//loop through all the tables in the subreport and
//set up the connection info and apply it to the tables
foreach (Table crTable in crTables)
{
location = crTable.Location;
crTableLogOnInfo = crTable.LogOnInfo;
crTableLogOnInfo.ConnectionInfo = crConnectInfo;
crTable.ApplyLogOnInfo(crTableLogOnInfo);
}
}
}
}
}
}
}
_user = "caps";
_passwd = "asdlkjqp";
This value is hardcoded, Irrespective of your input, it will always take this password. Try giving actual user / password instead of asdlkjqp
Is there some recommendation to build tables with cells having paragraphs in order to avoid an exception at adding of some cell to table or table to document? I get this and I can't figure out what happens:
[NullReferenceException: Object reference not set to an instance of an object.]
iText.Layout.Renderer.TableRenderer.DrawBorders(DrawContext drawContext) +2493
iText.Layout.Renderer.TableRenderer.DrawChildren(DrawContext drawContext) +1497
iText.Layout.Renderer.AbstractRenderer.Draw(DrawContext drawContext) +153
iText.Layout.Renderer.TableRenderer.Draw(DrawContext drawContext) +637
iText.Layout.Renderer.AbstractRenderer.DrawChildren(DrawContext drawContext) +104
iText.Layout.Renderer.BlockRenderer.Draw(DrawContext drawContext) +525
iText.Layout.Renderer.TableRenderer.DrawChildren(DrawContext drawContext) +1382
iText.Layout.Renderer.AbstractRenderer.Draw(DrawContext drawContext) +153
iText.Layout.Renderer.TableRenderer.Draw(DrawContext drawContext) +637
iText.Layout.Renderer.DocumentRenderer.FlushSingleRenderer(IRenderer resultRenderer) +473
iText.Layout.Renderer.RootRenderer.AddChild(IRenderer renderer) +1999
iText.Layout.RootElement`1.Add(BlockElement`1 element) +92
iText.Layout.Document.Add(BlockElement`1 element) +81
Here is a simple snapshot (compared to the real project) using a Windows console project:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iText.Layout;
using iText.Layout.Borders;
using iText.Layout.Element;
namespace iTextTest
{
public static class iTextSharpHelper
{
public static T SetBorderEx<T>(this ElementPropertyContainer<T> element, Border border)
where T : ElementPropertyContainer<T>
{
element.SetBorder(border);
return (T)element;
}
public static Paragraph Style(this BlockElement<Paragraph> element)
{
element
.SetBorderEx(iText.Layout.Borders.Border.NO_BORDER)
.SetFont(iText.Kernel.Font.PdfFontFactory.CreateFont(iText.IO.Font.FontConstants.HELVETICA))
.SetFontSize(10.0f)
.SetFixedLeading(12.0f)
.SetVerticalAlignment(iText.Layout.Properties.VerticalAlignment.BOTTOM)
.SetMargin(0f);
return (Paragraph)element;
}
}
class Program
{
private static float[] tableColumns = { 0.35f, 0.25f, 0.15f, 0.25f };
static void Main(string[] args)
{
iText.Kernel.Pdf.PdfDocument pdf = new iText.Kernel.Pdf.PdfDocument(new iText.Kernel.Pdf.PdfWriter("test.pdf"));
iText.Layout.Document document = new iText.Layout.Document(pdf, iText.Kernel.Geom.PageSize.A4);
document.SetMargins(50f, 50f, 25f, 50f);
iText.Layout.Element.Table mainTable = new iText.Layout.Element.Table(tableColumns)
.SetBorderEx(iText.Layout.Borders.Border.NO_BORDER)
.SetWidthPercent(100)
.SetHorizontalAlignment(iText.Layout.Properties.HorizontalAlignment.LEFT)
.SetPadding(0f);
for (int i = 0; i < 10; i++)
{
AddRow(mainTable, "ABCDEFGHIJ", "ABCDEFGHIJ", "ABCDEFGHIJ");
}
document.Add(mainTable);
document.Close();
}
private static void AddRow(iText.Layout.Element.Table table, string col1, string col2, string col3)
{
// Label
AddCell(table, col1, true)
.SetBorderTop(new iText.Layout.Borders.SolidBorder(iText.Kernel.Colors.Color.BLACK, 0.5f));
// Product - Voucher and price/pcs
AddCell(table, col2, true)
.SetBorderTop(new iText.Layout.Borders.SolidBorder(iText.Kernel.Colors.Color.BLACK, 0.5f));
// Message
AddCell(table, col3, true, 2)
.SetBorderTop(new iText.Layout.Borders.SolidBorder(iText.Kernel.Colors.Color.BLACK, 0.5f))
//.SetBorderRight(new iText.Layout.Borders.SolidBorder(iText.Kernel.Colors.Color.BLACK, 0.5f))
.SetHorizontalAlignment(iText.Layout.Properties.HorizontalAlignment.RIGHT)
.SetTextAlignment(iText.Layout.Properties.TextAlignment.RIGHT);
}
private static iText.Layout.Element.Cell AddCell(iText.Layout.Element.Table table, string text, bool setBold = false, int colSpan = 1)
{
iText.Layout.Element.Cell cell = new iText.Layout.Element.Cell(1, colSpan)
.SetBorderEx(iText.Layout.Borders.Border.NO_BORDER)
.SetVerticalAlignment(iText.Layout.Properties.VerticalAlignment.BOTTOM);
if (!string.IsNullOrEmpty(text))
{
iText.Layout.Element.Paragraph paragraph = new iText.Layout.Element.Paragraph(text)
.Style();
if (setBold)
paragraph.SetBold();
cell.Add(paragraph);
}
table.AddCell(cell);
return cell;
}
}
}
Note, a commented out line of code:
//.SetBorderRight(new iText.Layout.Borders.SolidBorder(iText.Kernel.Colors.Color.BLACK, 0.5f))
Adding it serves as a workaround to make the document render without the exception.
Given the sample code added by the OP the issue can easily be reproduced.
Furthermore after porting the code to iText/Java the issue could be reproduced there, too, cf. MikesTableIssue.java test method testMikesCode. Thus, it is no porting error from Java (the original iText code) to C#.
The sample could even be considerably simplified and still reproduce the issue:
try ( FileOutputStream target = new FileOutputStream("mikesTableIssueSimple.pdf");
PdfWriter pdfWriter = new PdfWriter(target);
PdfDocument pdfDocument = new PdfDocument(pdfWriter) )
{
Document document = new Document(pdfDocument);
Table mainTable = new Table(1);
Cell cell = new Cell()
.setBorder(Border.NO_BORDER)
//.setBorderRight(new SolidBorder(Color.BLACK, 0.5f))
.setBorderTop(new SolidBorder(Color.BLACK, 0.5f));
cell.add("TESCHTINK");
mainTable.addCell(cell);
document.add(mainTable);
}
(MikesTableIssue.java test method testSimplified)
The issue does not occur if one
removes setBorder(Border.NO_BORDER) or
removes setBorderTop(new SolidBorder(Color.BLACK, 0.5f)) or
adds setBorderRight(new SolidBorder(Color.BLACK, 0.5f)).
In this situation com.itextpdf.layout.renderer.TableRenderer.drawBorders(DrawContext) executes this code:
if (lastBorder != null) {
if (verticalBorders.get(j).size() > 0) {
if (i == 0) {
x2 += verticalBorders.get(j).get(i).getWidth() / 2;
} else if(i == horizontalBorders.size() - 1 && verticalBorders.get(j).size() >= i - 1 && verticalBorders.get(j).get(i - 1) != null) {
x2 += verticalBorders.get(j).get(i - 1).getWidth() / 2;
}
}
lastBorder.drawCellBorder(drawContext.getCanvas(), x1, y1, x2, y1);
}
while lastBorder is the SolidBorder instance, verticalBorders is [[null], [null]], j == 1 and i == 0.
Thus, some additional null checks ought to be introduced here.
sorry if this was posted earlier
I need to print list of expenses in a pdf document. the list may extend to any number of pages.
i'm writing the list by iterating the datarow object. One important thing is whenever the current page is going to end need to print the running total at the end of the page. i've wrote a class that implements PdfPageEventHandler as below
public class PaymentPageEventHandler : iTextSharp.text.pdf.PdfPageEventHelper
{
PdfContentByte cb;
private string subTotal = "";
public string GetSubtotal
{
set{
value = subTotal;
}
get
{
return subTotal;
}
}
public override void OnEndPage(PdfWriter writer, Document document)
{
// base.OnEndPage(writer, document);
cb = writer.DirectContent;
float[] iOuterTblWidth = { 10, 40F, 8, 12, 10 }; column widths of the table.
PdfPTable pdftbl = new PdfPTable(iOuterTblWidth);
PdfPCell cell = new PdfPCell();
cell.Colspan = 4;
cell.AddElement(new Chunk("Sub-Total"));
cell.HorizontalAlignment = 0;
pdftbl.AddCell(cell);
cell = new PdfPCell();
cell.AddElement(new Chunk(GetSubtotal));
cell.HorizontalAlignment = 2;
pdftbl.AddCell(cell);
}
}
the onEndPAge event above tries to write two columns. the above code gets called but the rows are not appearing in the pdf page.
I'm calling the above class like below
PaymentPageEventHandler ppem = new PaymentPageEventHandler();
ppem.GetSubtotal = "123"; // test value to print as running total
writer.PageEvent = ppem; // assigning event to writer object
Should i call explicity the PdfContentByte variable cb to write. if so how should i write the cells to the pdf.
can any one help me out on this.
You need to add the table using the WriteSelectedRows method. Please read the documentation and take a look at this example (or the C# ports of the examples)
Look for the line:
table.WriteSelectedRows(0, -1, 34, 803, writer.DirectContent);
Obviously, you'll need to adapt the coordinates.
I am dealing with a problem with annotatedtimelines.
I have to draw some charts depending on the tab that the user is, so when the tab is changed I clean the current chart and draw the new data. But how to do that?
For now I am removing all the rows, but it is not working.
Can someone help me?
here is the code:
...
//Creating Columns
dataTable.addColumn(ColumnType.DATETIME, "Time");
dataTable.addColumn(ColumnType.NUMBER, "Realtime Consumption");
dataTable.addColumn(ColumnType.NUMBER, "Historical Consumption");
//Create options
options.setDisplayAnnotations(false);
options.setDisplayZoomButtons(false);
options.setScaleType(AnnotatedTimeLine.ScaleType.FIXED);
options.setLegendPosition(AnnotatedTimeLine.AnnotatedLegendPosition.SAME_ROW);
options.setAllowRedraw(true);
options.setDisplayRangeSelector(false);
options.setFill(30);
//to parse the time
DateTimeFormat dtf = DateTimeFormat.getFormat("hh:mm:ss");
//For each item of the list
for(int i = 0; i < list.size(); i++){
//get date
Date date = new Date(list.getTimeAt(i));
//get hh:mm:ss
String time = date.getHours()+":"+date.getMinutes()+":"+date.getSeconds();
//add row
dataTable.addRow();
dataTable.setValue(dataTable.getNumberOfRows() - 1, 0, dtf.parse(time));
dataTable.setValue(dataTable.getNumberOfRows() - 1, 2, list.getDataAt(i));
}
/**
* To clean the chart
*/
public void cleanChart(){
//Remove all rows
this.dataTable.removeRows(0, dataTable.getNumberOfRows());
//Redraw the chart
this.draw(this.dataTable, this.options);
}
Thanks,
MaurĂcio
It is very strange, but I did it (that seems ok, because I'd create another datatable), and it still not working. The old data continues there.
I have a class that extends AnnotatedTimeLine, and the clean method is now:
/**
* Method to clean the annotated time line
*/
public void clean() {
//Create new table
this.dataTable = DataTable.create();
//Create columns
this.dataTable.addColumn(ColumnType.DATETIME, "Time");
this.dataTable.addColumn(ColumnType.NUMBER, "Data 1");
this.dataTable.addColumn(ColumnType.NUMBER, "Data 2");
//Redraw the chart with the same options
this.draw(this.dataTable, this.options);
}
Any idea?
Thanks!
You need to recreate DataTable for your new data and don't need to do
this.dataTable.removeRows(0, dataTable.getNumberOfRows());
I have something like this
public void reloadChart(List<SharedBean> list, String titleX) {
viz.draw(getChartData(), getOptions(titleX));
}
private DataTable getChartData() {
DataTable data = DataTable.create();
data.addColumn(ColumnType.STRING, "column");
data.addColumn(ColumnType.NUMBER, "value");
data.addRows(list.size());
int row = 0;
int i = 0;
for(SharedBean bean: list){
......
}
return data;
}
Hello all
I am using smart gwt 2.2 on windows with mozilla browser.
I am using a list grid with two fields.
I set the editor type of second field to SelectItem.
In that select item I am rendering a grid.
For select item I set the value field and the display field.
But after the select any item from select item it is display value field.
I am also attaching the code for it.
code for grid
public void initializeGrid() {
ListGrid grid = new ListGrid();
setGridProperty(grid);
grid.setFields(getGridFields());
grid.setData(getGridData());
getSmartContainer().addChild(grid);
}
private static ListGridRecord[] getGridData() {
ListGridRecord record = new ListGridRecord();
record.setAttribute("id", "");
record.setAttribute("name", "");
ListGridRecord record1 = new ListGridRecord();
record1.setAttribute("id", "");
record1.setAttribute("name", "");
return new ListGridRecord[] { record, record1 };
}
private static void setGridProperty(ListGrid grid) {
grid.setWidth("90%");
grid.setHeight(125);
grid.setCanEdit(true);
grid.setEditEvent(ListGridEditEvent.CLICK);
grid.setEditByCell(true);
grid.setAlternateRecordStyles(true);
grid.setShowAllRecords(true);
}
private static ListGridField[] getGridFields() {
ListGridField field = new ListGridField("id");
FormItem item = new TextItem();
field.setEditorType(item);
ListGridField field1 = new ListGridField("name");
SelectItem item1 = new SelectItem("name");
setPropertyForSelectitem(item1);
DataSource dataSource = new DataSource();
dataSource.setClientOnly(true);
item1.setOptionDataSource(dataSource);
setDataForSelectItem(dataSource);
field1.setEditorType(item1);
return new ListGridField[] { field, field1 };
}
Code for select item
public static void setDataForSelectItem(DataSource dataSource) {
for (int i = 0; i < 2; i++) {
ListGridRecord record = new ListGridRecord();
record.setAttribute("id", "1");
record.setAttribute("name", "name" + i);
record.setAttribute("address", "address" + i);
dataSource.addData(record);
}
}
private static void setPropertyForSelectitem(SelectItem item) {
item.setPickListFields(getFieldsForSelectItem());
item.setWidth(150);
item.setValueField("id");
item.setDisplayField("name");
item.setPickListWidth(250);
}
private static ListGridField[] getFieldsForSelectItem() {
ListGridField idField = new ListGridField("id");
ListGridField nameField = new ListGridField("name");
ListGridField addField = new ListGridField("address");
return new ListGridField[] {idField,nameField,addField };
}
[/CODE]
After drawing this grid it is rendering value field for the select item, but i want to render the name (as it is the display field for the select item).
Same select item I used in the dynamic form but it is working well at that place, but for the grid it is not working well.
Please Help.
Thanks