Epplus - Cannot change cell value or cell header - epplus

I have a problem when change the value of a cell. Here is my code:
FileInfo newFile = new FileInfo(file); ExcelPackage pck = new ExcelPackage(newFile);
var wsData = pck.Workbook.Worksheets.Add("Absent Employee List");
var dataRange = wsData.Cells["A1"].LoadFromCollection(
from s in emps
orderby s.EmployeeCode
select s,
true, OfficeOpenXml.Table.TableStyles.Medium2
);
wsData.Cells[2, 4, dataRange.End.Row, 4].Style.Numberformat.Format = "dd-mm-yyyy"
wsData.Cells[2, 5, dataRange.End.Row, 5].Style.Numberformat.Format = "dd-mm-yyyy";
wsData.Cells["A1"].Value = "Employee Code"; // [1, 1]
wsData.Cells["B1"].Value = "Full Name"; // [1, 2]
wsData.Cells["C1"].Value = "Department"; // [1, 3]
dataRange.AutoFitColumns();
pck.SaveAs(newFile);
When I open the file after creating, the header of A1, B1, C1 didn't change. Did i miss something? thank you for your help.

Try this
wsData.Cells[1,1].Value = "Employee Code";
wsData.Cells[2,1].Value = "Full Name";
wsData.Cells[3,1].Value = "Department";
This is what worked for me!

This was a bug in the library, it has been fixed in a prior release.
You can find the bug description as well as a workaround here:
https://epplus.codeplex.com/workitem/15245
ExcelTable excelTable = this.worksheet.Tables[0];
excelTable.Columns[1].Name = "Test";

Related

Replace existng column in MSR

Why does the following MSR code not replace the original column "Var1"?
rxDataStep(inData = input_xdf, outFile = input_xdf, overwrite = TRUE,
transforms = list(Var1 = as.numeric(Var1)),
transformVars = c("Var1")
)
At the moment, RevoScaleR doesn't support changing the type of a variable in an xdf file (even if you write to a different file). The way to do it is to create a new variable, drop the old, and then rename the new variable to the old name.
I would suggest doing this with a transformFunc (see ?rxTransform for more information), so that you can create the new variable and drop the old, all in one step:
rxDataStep(inXdf, outXdf, transformFunc=function(varlst) {
varlst$Var1b <- as.numeric(varlst$Var1)
varlst$Var1 <- NULL
varlst
}, transformVars="Var1")
# this is fast as it only modifies the xdf metadata, not the data itself
names(outXdf)[names(outXdf) == "Var1b"] <- "Var1"
MSR doesn't allow you to overwrite a variable in place with a different variable type.
You have two options: Write to a different variable or write to a different file. I have added a bit of code that shows that both solutions work as stated in MRS 9.0.1. As stated in the comments, there is some point in earlier versions where this might not work. I am not totally sure where that point is, so the code should let you know.
input_xdf <- "test.xdf"
modified_xdf <- "test_out.xdf"
xdf_data <- data.frame(Var1 = as.character(1:10),
Var2 = 2:11,
stringsAsFactors = FALSE)
rxDataStep(inData = xdf_data,
outFile = input_xdf,
rowsPerRead = 5,
overwrite = TRUE)
rxDataStep(inData = input_xdf,
outFile = input_xdf,
overwrite = TRUE,
transforms = list(Var1b = as.numeric(Var1)),
transformVars = c("Var1")
)
rxGetInfo(input_xdf, getVarInfo = TRUE, numRows = 5)
rxDataStep(inData = input_xdf,
outFile = modified_xdf,
transforms = list(Var1 = as.numeric(Var1)),
transformVars = c("Var1")
)
rxGetInfo(modified_xdf, getVarInfo = TRUE, numRows = 5)

display data labels column stacked epplus

I have a stacked column report and i need to show the label value inside each of the series, is this possible. here is the code i have so far. It does look like barcharts have this option, not sure if i need to convert report to that type.
chart.Title.Text = "Total Pipeline - Initiative Count by Release";
chart.Title.Font.Size = 8;
chart.SetPosition(45, 0, 3, 0);
chart.SetSize(400, 300);
chart.Legend.Add();
chart.YAxis.MajorUnit = 10;
var series1 = chart.Series.Add(Chartsheet.Cells["L23:Q23"], Chartsheet.Cells["L22:Q22"]);
series1.HeaderAddress = new ExcelAddress("'Graphs'!K23");
var series2 = chart.Series.Add(Chartsheet.Cells["L24:Q24"], Chartsheet.Cells["L22:Q22"]);
series2.HeaderAddress = new ExcelAddress("'Graphs'!K24");
chart.Legend.Position = eLegendPosition.Bottom;
chart.YAxis.LabelPosition = eTickLabelPosition.NextTo;
chart.XAxis.MajorTickMark = eAxisTickMark.Out;
chart.XAxis.MinorTickMark = eAxisTickMark.None;
chart.ShowDataLabelsOverMaximum = true;
so i just forced a format of a barchart and i have the label option
var chart = (OfficeOpenXml.Drawing.Chart.ExcelBarChart) Chartsheet.Drawings.AddChart("chart", eChartType.ColumnStacked);

Automatic PDF Rendering

I've read the MigraDoc/PdfSharp documentation, but it feels a bit thin. I want to render out a PDF, but not have to manually specify width and height. I just want it to align right, center, or left (of margins), and handle all the sizing for me.
Public Sub Write()
Dim document As PdfDocument = New PdfDocument()
Dim page As PdfPage = document.AddPage()
Dim gfx As XGraphics = XGraphics.FromPdfPage(page)
gfx.MUH = PdfFontEncoding.Unicode
gfx.MFEH = PdfFontEmbedding.Default
Dim font As XFont = New XFont("Verdana", 13, XFontStyle.Bold)
Dim migraDocument As New Document
Dim sec As Section = migraDocument.AddSection()
Dim quotationHeader As New Paragraph
quotationHeader.AddText("Quotation" & vbNewLine)
quotationHeader.Format.Alignment = ParagraphAlignment.Right
sec.Add(quotationHeader)
Dim dhAddressInfo As New Paragraph
dhAddressInfo.AddText("ADDRESS GOES HERE")
dhAddressInfo.Format.Alignment = ParagraphAlignment.Left
sec.Add(dhAddressInfo)
Dim quotationInfo As New Paragraph
quotationInfo.AddText("QUOTATION INFO AND DATE HERE")
quotationInfo.Format.Alignment = ParagraphAlignment.Right
sec.Add(quotationInfo)
Dim customerBilling As New Paragraph
With Customer
customerBilling.AddText("CUSTOMER BILLING OBJECT PROPERTIES HERE")
End With
customerBilling.Format.Alignment = ParagraphAlignment.Left
sec.Add(customerBilling)
Dim authorInfo As New Paragraph
authorInfo.AddText("AUTHOR INFO HERE")
authorInfo.Format.Alignment = ParagraphAlignment.Right
sec.Add(authorInfo)
Dim pricingTable As New Table
'pricingTable.Format.Alignment = ParagraphAlignment.Center
pricingTable.AddColumn("13cm")
pricingTable.AddColumn("13cm")
Dim headerRow As New Row
headerRow = pricingTable.AddRow()
headerRow.HeadingFormat = True
headerRow.Cells(0).AddParagraph("Description")
headerRow.Cells(1).AddParagraph("Amount")
For i As Integer = 0 To SelectedPrices.Count - 1
Dim row As Row = pricingTable.AddRow()
Dim price As Pricing = SelectedPrices(i)
row.Cells(0).AddParagraph(price.Item)
row.Cells(1).AddParagraph(price.Price * price.Quantity)
Next
Dim totalRow As Row = pricingTable.AddRow()
totalRow.Cells(0).AddParagraph("Total: ")
Dim total As Double = 0
For Each price As Pricing In SelectedPrices
total = total + (price.Price * price.Quantity)
Next
totalRow.Cells(1).AddParagraph(total.ToString)
sec.Add(pricingTable)
Dim docRenderer As DocumentRenderer = New DocumentRenderer(migraDocument)
docRenderer.PrepareDocument()
docRenderer.RenderObject(gfx, XUnit.FromCentimeter(0), XUnit.FromCentimeter(0), "10cm", quotationHeader)
docRenderer.RenderObject(gfx, XUnit.FromCentimeter(0), XUnit.FromCentimeter(2), "10cm", dhAddressInfo)
docRenderer.RenderObject(gfx, XUnit.FromCentimeter(5), XUnit.FromCentimeter(2), "10cm", quotationInfo)
docRenderer.RenderObject(gfx, XUnit.FromCentimeter(0), XUnit.FromCentimeter(6), "10cm", customerBilling)
docRenderer.RenderObject(gfx, XUnit.FromCentimeter(5), XUnit.FromCentimeter(6), "10cm", authorInfo)
docRenderer.RenderObject(gfx, XUnit.FromCentimeter(3), XUnit.FromCentimeter(10), "10cm", pricingTable)
document.Save(Environment.CurrentDirectory & "\test.pdf")
End Sub
Notice at the bottom I'm specifying the X and Y coordinates of each section. I just want to define spacing. Alignment should take care of the rest.
I found a different tutorial that uses PdfDocumentRenderer and shows how to correctly use it. It's not in VB, but quite easily translated. I copied it below in case the link goes dead.
http://www.c-sharpcorner.com/UploadFile/aftab_ku/create-object-model-document-and-renders-them-into-pdf/
public Document CreateDocument()
{
// Create a new MigraDoc document
this.document = new Document();
this.document.Info.Title = "";
this.document.Info.Subject = "";
this.document.Info.Author = "Aftab";
DefineStyles();
CreatePage();
FillContent();
return this.document;
}
Here, CreateDocument() in PDFform.cs creates a new MigraDoc. Take a look at the three functions called for creating style and page and fill the content of the tables.
//
void DefineStyles()
{
// Get the predefined style Normal.
Style style = this.document.Styles["Normal"];
// Because all styles are derived from Normal, the next line changes the
// font of the whole document. Or, more exactly, it changes the font of
// all styles and paragraphs that do not redefine the font.
style.Font.Name = "Verdana";
style = this.document.Styles[StyleNames.Header];
style.ParagraphFormat.AddTabStop("16cm", TabAlignment.Right);
style = this.document.Styles[StyleNames.Footer];
style.ParagraphFormat.AddTabStop("8cm", TabAlignment.Center);
// Create a new style called Table based on style Normal
style = this.document.Styles.AddStyle("Table", "Normal");
style.Font.Name = "Verdana";
style.Font.Name = "Times New Roman";
style.Font.Size = 9;
// Create a new style called Reference based on style Normal
style = this.document.Styles.AddStyle("Reference", "Normal");
style.ParagraphFormat.SpaceBefore = "5mm";
style.ParagraphFormat.SpaceAfter = "5mm";
style.ParagraphFormat.TabStops.AddTabStop("16cm", TabAlignment.Right);
}
DefineStyles() does the job of styling the document:
void CreatePage()
{
// Each MigraDoc document needs at least one section.
Section section = this.document.AddSection();
// Put a logo in the header
Image image= section.AddImage(path);
image.Top = ShapePosition.Top;
image.Left = ShapePosition.Left;
image.WrapFormat.Style = WrapStyle.Through;
// Create footer
Paragraph paragraph = section.Footers.Primary.AddParagraph();
paragraph.AddText("Health And Social Services.");
paragraph.Format.Font.Size = 9;
paragraph.Format.Alignment = ParagraphAlignment.Center;
............
// Create the item table
this.table = section.AddTable();
this.table.Style = "Table";
this.table.Borders.Color = TableBorder;
this.table.Borders.Width = 0.25;
this.table.Borders.Left.Width = 0.5;
this.table.Borders.Right.Width = 0.5;
this.table.Rows.LeftIndent = 0;
// Before you can add a row, you must define the columns
Column column;
foreach (DataColumn col in dt.Columns)
{
column = this.table.AddColumn(Unit.FromCentimeter(3));
column.Format.Alignment = ParagraphAlignment.Center;
}
// Create the header of the table
Row row = table.AddRow();
row.HeadingFormat = true;
row.Format.Alignment = ParagraphAlignment.Center;
row.Format.Font.Bold = true;
row.Shading.Color = TableBlue;
for (int i = 0; i < dt.Columns.Count; i++)
{
row.Cells[i].AddParagraph(dt.Columns[i].ColumnName);
row.Cells[i].Format.Font.Bold = false;
row.Cells[i].Format.Alignment = ParagraphAlignment.Left;
row.Cells[i].VerticalAlignment = VerticalAlignment.Bottom;
}
this.table.SetEdge(0, 0, dt.Columns.Count, 1, Edge.Box,
BorderStyle.Single, 0.75, Color.Empty);
}
Here CreatePage() adds a header, footer, and different sections into the document and then the table is created to display the records. Columns from the datatable are added into the table inside the document and then a header row that contains the column names is added.
column = this.table.AddColumn(Unit.FromCentimeter(3));
//creates a new column and width of the column is passed as a parameter.
Row row = table.AddRow();
//A new header row is created
row.Cells[i].AddParagraph(dt.Columns[i].ColumnName);
//this will add the column name to header of the row.
this.table.SetEdge(0, 0, dt.Columns.Count, 1, Edge.Box,
BorderStyle.Single, 0.75, Color.Empty);
//sets the border of the row
void FillContent()
{
...............
Row row1;
for (int i = 0; i < dt.Rows.Count; i++)
{
row1 = this.table.AddRow();
row1.TopPadding = 1.5;
for (int j = 0; j < dt.Columns.Count; j++)
{
row1.Cells[j].Shading.Color = TableGray;
row1.Cells[j].VerticalAlignment = VerticalAlignment.Center;
row1.Cells[j].Format.Alignment = ParagraphAlignment.Left;
row1.Cells[j].Format.FirstLineIndent = 1;
row1.Cells[j].AddParagraph(dt.Rows[i][j].ToString());
this.table.SetEdge(0, this.table.Rows.Count - 2, dt.Columns.Count, 1,
Edge.Box, BorderStyle.Single, 0.75);
}
}
.............
}
FillContent() fills the rows from the datatable into the table inside the document:
row1.Cells[j].AddParagraph(dt.Rows[i][j].ToString());
//adds the value of column into the table row
The Default.aspx file contains the code for generating the PDF:
using MigraDoc.DocumentObjectModel;
using MigraDoc.Rendering;
using System.Diagnostics;
MigraDoc libraries are used for generating PDF documents, and System.Diagnostics for starting a PDF Viewer:
PDFform pdfForm = new PDFform(GetTable(), Server.MapPath("img2.gif"));
// Create a MigraDoc document
Document document = pdfForm.CreateDocument();
document.UseCmykColor = true;
// Create a renderer for PDF that uses Unicode font encoding
PdfDocumentRenderer pdfRenderer = new PdfDocumentRenderer(true);
// Set the MigraDoc document
pdfRenderer.Document = document;
// Create the PDF document
pdfRenderer.RenderDocument();
// Save the PDF document...
string filename = "PatientsDetail.pdf";
pdfRenderer.Save(filename);
// ...and start a viewer.
Process.Start(filename);
The PdfForm object is created and using it, a new MigraDoc is generated. PdfDocumentRenderer renders the PDF document and then saves it. Process.Start(filename) starts a PDF viewer to open the PDF file created using MigraDoc.

Modify value at the time of binding DataGrid Compact Framwork

I have used BindingSource to bind DataGrid in my window 6.5 application. But problem is that I want to change the text of a column from Int to string while grid is binding.
If you look at below code I am binding DataGrid with Designation which value is 502 but I need to display "SE" instead, I cant take that value in my Candidate object so I need to modify DataGrid at runtime. I dont know how can I achieve this. Please help . Thanks
cand.Add(new Candidate { ID = 10, Name = "Andrew", Designation =501 ,DCode="SSE" });
cand.Add(new Candidate { ID = 11, Name = "Peter", Designation = 502 , DCode="SE"});
DataGridTableStyle myDataGridTableStyle = new DataGridTableStyle();
myDataGridTableStyle.MappingName = "Candidate";
DataGridTextBoxColumn colA = new DataGridTextBoxColumn();
colA.MappingName = "Name";
colA.HeaderText = "Field A";
colA.Width = 50;
DataGridTextBoxColumn colB = new DataGridTextBoxColumn();
colB.MappingName = "Designation";
colB.HeaderText = "Position Holding";
colB.Width = 100;
//dataGrid1.CurrentCell.ColumnNumber.
DataGridTextBoxColumn colC = new DataGridTextBoxColumn();
colC.MappingName = "DCode";
colC.HeaderText = "Code Position";
colC.Width = 50;
myDataGridTableStyle.GridColumnStyles.Add(colA);
myDataGridTableStyle.GridColumnStyles.Add(colB);
myDataGridTableStyle.GridColumnStyles.Add(colC);
myBindingSource.DataSource = cand.ToBindingList();
myDataGridTableStyle.MappingName = myBindingSource.GetListName(null);
dataGrid1.TableStyles.Clear(); // Recommended on MSDN in the code examples.
dataGrid1.TableStyles.Add(myDataGridTableStyle);
dataGrid1.DataSource = myBindingSource;
Why don't you make the DCode property a slave to your Designation property so that:
Canidate c = new Candidate();
c.Designation = 501;
print(c.DCode);//outputs "SSE"
then you can bind to DCode when you just want the string interpretation of Designation.

How to get the datatype of column from the sharepoint list?

I want to get or retrieve the datatype of a particular column where
the list is created in a sharepoint list.
Can you help me for doing the task?
See SPField.Type (or SPField.TypeDisplayName).
SPList list = web.Lists["my list"];
SPField field = list.Fields["particular"];
SPFieldType fieldType = field.Type;
string fieldTypeName = field.TypeDisplayName;
Building off of Rich Bennema's answer (referencing the Microsoft.SharePoint.Client and Microsoft.SharePoint.Client.RunTime version 16 libriaries and using the Microsoft.SharePoint.Client name space):
using (ClientContext cont = new ClientContext(SharePointUrl))
{
cont.Credentials = new SharePointOnlineCredentials(Username, SecurePassword);
FieldCollection fields = cont.Web.Lists.GetByTitle(SharePointListName).Fields;
cont.Load(fields);
cont.ExecuteQuery();
var results =
fields.Select(
f => new
{
f.InternalName,
f.TypeDisplayName,
TextMaxLength = (f is FieldText) ? ((FieldText)f).MaxLength : 0,
FieldChoices = (f is FieldChoice) ? ((FieldChoice)f).Choices : new string[0]
}
);
}