how to create radiobutton list using itextsharp in c# - asp.net

i am trying to make radiobutton list in pdf file using itextsharp but it create box.
Is there anyone can say me why this is happening ?
for (int j = 0; j < 8; j++)
{
Rectangle(0, 0, 22, 22), "RadioButtons_" + j.ToString(), "On");
Rectangle _rect;
_rect = new Rectangle(100, 100, 100, 100);
radios[j] = new RadioCheckField(writer, _rect, "RadioButtons_" + j.ToString(), "On");
radios[j].BackgroundColor = new GrayColor(0.8f);
radios[j].BorderColor = GrayColor.BLACK;
radios[j].CheckType = RadioCheckField.TYPE_CIRCLE;
cell = new PdfPCell();
if (j == 6)
{
cell.Colspan = 3;
radios[j].Text = " Not Important";
}
else if (j == 7)
{
cell.Colspan = 3;
radios[j].Text = "Not Applicable";
}
else
{
cell.Colspan = 1;
}
kid = new iTextSharp.text.pdf.events.FieldPositioningEvents(writer, radios[j].CheckField, "radios");
kid.Padding = 0.5f;
cell.CellEvent = kid;
table.AddCell(cell);
}

Related

while export to pdf using itexsharp it shows blank page

i made one desktop application using asp.net which convert html to PDF.
basically this application used for generate users PDF from database.
process: first of all i am converting all data to html and then convert to PDF using itextsharp but after generating some PDFs it shows blank pages
any idea or anyone face this type of issue
public static void converttopdf(string HtmlStream, List<Tuple<string, string>> tifffiles, List<Tuple<string, string>> pdffilestomerge, string filename, string patientfirstpagestr, string TableofContent, string patientheader, SqlConnection con, string sectiondetails)
{
MemoryStream msOutput = new MemoryStream();
TextReader reader = new StringReader(HtmlStream);
Document document = new Document(PageSize.A4, 30, 30, 42, 44);
string filetogenerate = string.Empty;
if (pdffilestomerge != null && pdffilestomerge.Count > 1)
{
filetogenerate = temppath + filename + "_Temp1.pdf";
}
else
{
filetogenerate = temppath + filename + "_Temp.pdf";
}
PdfWriter writer = PdfWriter.GetInstance(document, new System.IO.FileStream(filetogenerate, System.IO.FileMode.Create));
HTMLWorker worker = new HTMLWorker(document);
document.Open();
worker.StartDocument();
string[] separator = new string[] { #"<br clear='all' style='page-break-before:always'>" };
string[] pages = HtmlStream.Split(separator, StringSplitOptions.None);
foreach (string page in pages)
{
document.NewPage();
System.Collections.ArrayList htmlarraylist = HTMLWorker.ParseToList(new StringReader(page), null);
for (int k = 0; k < htmlarraylist.Count; k++)
{
document.Add((IElement)htmlarraylist[k]);
}
}
using (var ms = new MemoryStream())
{
if (tifffiles != null)
{
int docid = 0;
foreach (var obj in tifffiles)
{
string filepath = obj.Item2.ToString();
WriteLogEntry("bitmap file path : " + filepath);
if (filepath != string.Empty)
{
try
{
Bitmap myBitmap = new Bitmap(filepath);
System.Drawing.Color pixelColor = myBitmap.GetPixel(50, 50);
if (pixelColor.Name == "ff808080")
{
WriteLogEntry("convert image by irfanview :" + filepath);
LaunchCommandLineApp(filepath, temppath + "Test.jpg");
document.NewPage();
var imgStream = GetImageStream(temppath + "Test.jpg");
var image = iTextSharp.text.Image.GetInstance(imgStream);
image.SetAbsolutePosition(10, 80);
image.ScaleToFit(document.PageSize.Width - 60, document.PageSize.Height - 80);
//image.ScaleToFit(document.PageSize.Width - 30, document.PageSize.Height);
if (docid != Convert.ToInt32(obj.Item1))
{
Chunk c1 = new Chunk("#~#DID" + obj.Item1.ToString() + "#~#");
c1.Font.SetColor(0, 0, 0); //#00FFFFFF
c1.Font.Size = 0;
document.Add(c1);
}
document.Add(image);
File.Delete(temppath + "Test.jpg");
}
else
{
document.NewPage();
var imgStream = GetImageStream(filepath);
var image = iTextSharp.text.Image.GetInstance(imgStream);
image.SetAbsolutePosition(10, 80);
image.ScaleToFit(document.PageSize.Width - 60, document.PageSize.Height - 80);
//image.ScaleToFit(document.PageSize.Width - 30, document.PageSize.Height);
if (docid != Convert.ToInt32(obj.Item1))
{
Chunk c1 = new Chunk("#~#DID" + obj.Item1.ToString() + "#~#");
c1.Font.SetColor(0, 0, 0); //#00FFFFFF
c1.Font.Size = 0;
document.Add(c1);
}
document.Add(image);
WriteLogEntry("Image added successfully" + filepath);
}
}
catch
{
document.NewPage();
if (docid != Convert.ToInt32(obj.Item1))
{
Chunk c1 = new Chunk("#~#DID" + obj.Item1.ToString() + "#~#");
c1.Font.SetColor(0, 0, 0); //#00FFFFFF
c1.Font.Size = 0;
document.Add(c1);
}
WriteLogEntry("Image not valid" + filepath);
}
docid = Convert.ToInt32(obj.Item1);
}
}
}
}
worker.EndDocument();
worker.Close();
document.Close();
if (pdffilestomerge != null && pdffilestomerge.Count > 1)
{
string file = temppath + filename + "_Temp.pdf";
mergepdf(file, pdffilestomerge, filetogenerate);
}
PdfReader pdfreader = new PdfReader(temppath + filename + "_Temp.pdf");
Document document1 = new Document(PageSize.A4, 30, 30, 42, 44);
PdfWriter writer1 = PdfWriter.GetInstance(document1, new FileStream(FinalOutputPath + filename + ".pdf", FileMode.Create));
//HeaderFooter footer = new HeaderFooter(new Phrase("Page "), true);
//footer.Alignment = Element.ALIGN_RIGHT;
//footer.Border = iTextSharp.text.Rectangle.NO_BORDER;
//document1.Footer = footer;
//HeaderFooter header = new HeaderFooter(new Phrase(""), true);
//header.Alignment = Element.ALIGN_LEFT;
//header.Border = iTextSharp.text.Rectangle.NO_BORDER;
//document1.Add(header);
document1.Open();
PdfContentByte cb1 = writer1.DirectContent;
PdfImportedPage page1;
string test1 = TableofContent; int TableofContentPageCount = 0; int SectionPageStartNumber = 0;
string lastdocnamestr = "";
for (int t = 1; t <= pdfreader.NumberOfPages; t++)
{
document1.NewPage();
HeaderFooter header = new HeaderFooter(new Phrase(""), true);
header.Alignment = Element.ALIGN_LEFT;
header.Border = iTextSharp.text.Rectangle.NO_BORDER;
HeaderFooter header1 = new HeaderFooter(new Phrase(" "), true);
header1.Alignment = Element.ALIGN_LEFT;
header1.Border = iTextSharp.text.Rectangle.NO_BORDER;
HeaderFooter header2 = new HeaderFooter(new Phrase(" "), true);
header2.Alignment = Element.ALIGN_LEFT;
header2.Border = iTextSharp.text.Rectangle.NO_BORDER;
document1.Add(header);
document1.Add(header1);
document1.Add(header2);
page1 = writer1.GetImportedPage(pdfreader, t);
var baseFont = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
byte[] pdfcontent = pdfreader.GetPageContent(t);
//PdfDictionary dict = pdfreader.GetPageN(t);
string contentStream = System.Text.Encoding.Default.GetString(pdfcontent);
var contentByte = writer1.DirectContent;
contentByte.BeginText();
contentByte.SetFontAndSize(baseFont, 8);
var multiLineString = "";
var multiLineString1 = "";
string test = getBetween(contentStream, "#~#", "#~#");
if (test.Length > 0)
{
test1 = test1.Replace(test + ".", t.ToString());
DataTable dt = getdocdetailforheader(Convert.ToInt32(test.Replace("DID", "")), con);
if (dt.Rows.Count > 0)
{
multiLineString = dt.Rows[0]["DocumentName"].ToString() + " - " + Convert.ToDateTime(dt.Rows[0]["EncounterDTTM"].ToString()).ToString("MM/dd/yyyy") + " | Owner : " + dt.Rows[0]["Ownername"].ToString();
lastdocnamestr = multiLineString;
WriteLogEntry(multiLineString);
}
if (TableofContentPageCount == 0)
{
TableofContentPageCount = t;
}
}
//if (contentStream.Contains("sectionstart") && SectionPageStartNumber == 0) SectionPageStartNumber = t;
if (lastdocnamestr != string.Empty)
{
multiLineString = lastdocnamestr;
}
//else
//{
// if (TableofContentPageCount == 0)
// {
// multiLineString = "Table of Content";
// }
//}
multiLineString1 = patientheader;
contentByte.ShowTextAligned(PdfContentByte.ALIGN_LEFT, multiLineString, 15, 820, 0);
contentByte.ShowTextAligned(PdfContentByte.ALIGN_LEFT, multiLineString1, 15, 810, 0);
contentByte.EndText();
string relLogo = Directory.GetCurrentDirectory().ToString().Replace("bin", "").Replace("Debug", "").Replace("\\\\", "") + "\\Image\\MFA_LOGO.png";
iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(relLogo);
jpg.ScaleAbsolute(38f, 38f);
jpg.SetAbsolutePosition(document1.PageSize.Width - 70, 806);
jpg.Alignment = Element.ALIGN_RIGHT;
document1.Add(jpg);
cb1.MoveTo(0, 805);
cb1.LineTo(document1.PageSize.Width, 805);
cb1.Stroke();
cb1.AddTemplate(page1, 0, 0);
}
SectionPageStartNumber = pdfreader.NumberOfPages + 1;
System.Collections.ArrayList htmlarraylist1 = HTMLWorker.ParseToList(new StringReader(sectiondetails), null);
document1.NewPage();
for (int k = 0; k < htmlarraylist1.Count; k++)
{
document1.Add((IElement)htmlarraylist1[k]);
}
document1.Close();
FinalPDF(FinalOutputPath + filename + ".pdf", FinalOutputPath + filename + "_1.pdf", patientfirstpagestr, test1, TableofContentPageCount, patientheader, SectionPageStartNumber);
File.Delete(temppath + filename + "_Temp.pdf");

Xamarin.Forms: Putting A Label Inside A BarChart Layout

I am using oxyplot to plot a bar chart. I wish to add an extra label in the chart. I've tried to use Textannotation but it's not showing on the chart. What is the mistake I'm making to cause the text not to appear, is it the DataPoint? Please help.
plotModel = new PlotModel
{
Title = "Daily",
LegendPlacement = LegendPlacement.Outside,
LegendPosition = LegendPosition.BottomCenter,
LegendOrientation = LegendOrientation.Horizontal,
LegendBorderThickness = 0
};
TextAnnotation txtlabel = new TextAnnotation();
txtlabel.Text = "Test";
txtlabel.TextColor = OxyColors.Red;
txtlabel.Stroke = OxyColors.Red;
txtlabel.StrokeThickness = 5;
txtlabel.FontSize = 36;
txtlabel.TextPosition = new DataPoint(21, 3.5);
plotModel.Annotations.Add(txtlabel);
string sPrevType = "";
string sCurrentType = "";
DateTime dtdate;
var sr = new ColumnSeries();
var col = new ColumnItem();
int iCount = 0;
List<decimal> lstI = new List<decimal>();
List<decimal> lstD = new List<decimal>();
List<decimal> lstS = new List<decimal>();
foreach (var itm in _dateodr)
{
dtdate = itm.date;
sCurrentType = itm.Type;
lstI.Add(itm.I_Unit);
lstD.Add(itm.D_Unit);
lstS.Add(itm.S_Unit);
if (sCurrentType != sPrevType && sPrevType != "")
{
sr = new ColumnSeries();
sr.Title = sPrevType;
sr.LabelPlacement = LabelPlacement.Outside;
sr.StrokeColor = OxyColors.Black;
sr.StrokeThickness = 1;
//sr.LabelFormatString = "{0:#,##0.00}";
plotModel.Series.Add(sr);
}
sPrevType = sCurrentType;
iCount += 1;
}
if (iCount == _dateodr.Count)
{
sr = new ColumnSeries();
sr.Title = sPrevType;
sr.LabelPlacement = LabelPlacement.Outside;
sr.StrokeColor = OxyColors.Black;
sr.StrokeThickness = 1;
//sr.LabelFormatString = "{0:#,##0.00}";
sr.FontSize = 10;
plotModel.Series.Add(sr);
}
for (int i = 0; i < iCount; i++)
{
ColumnSeries ssr = (ColumnSeries)plotModel.Series[i];
var colIm = new ColumnItem();
colIitm.Value = double.Parse(lstI[i].ToString()) / 1000;
ssr.Items.Add(colIitm);
var colDOitm = new ColumnItem();
colDitm.Value = double.Parse(lstD[i].ToString()) / 1000;
ssr.Items.Add(colDitm);
var colSitm = new ColumnItem();
colSitm.Value = double.Parse(lstS[i].ToString()) / 1000;
ssr.Items.Add(colSitm);
}
categoryaxis.Labels.Add("I");
categoryaxis.Labels.Add("Dr");
categoryaxis.Labels.Add("Sr");
switch (sUnitType)
{
case "2":
valueAxis = new LinearAxis { Position = AxisPosition.Left, MinimumPadding = 0, MaximumPadding = 0.06, AbsoluteMinimum = 0, Title = "m", Angle = 90, FontWeight = FontWeights.Bold, FontSize = 15 };
break;
case "qy":
valueAxis = new LinearAxis { Position = AxisPosition.Left, MinimumPadding = 0, MaximumPadding = 0.06, AbsoluteMinimum = 0, Title = "Qy", Angle = 90, FontWeight = FontWeights.Bold, FontSize = 15 };
break;
case "Am":
valueAxis = new LinearAxis { Position = AxisPosition.Left, MinimumPadding = 0, MaximumPadding = 0.06, AbsoluteMinimum = 0, Title = "Am", Angle = 90, FontWeight = FontWeights.Bold, FontSize = 15 };
break;
}
plotModel.Axes.Add(categoryaxis);
plotModel.Axes.Add(valueAxis);
}
PlotView plot = new PlotView
{
VerticalOptions = LayoutOptions.Fill,
HorizontalOptions = LayoutOptions.Fill,
BackgroundColor = Color.White,
Model = plotModel
};
Content = plot;

How to Export Multiple Datasets to Single ExcelSheet?

I am having two datasets in which first dataset has 6 rows and second dataset has 'N' Number of rows , second dataset row count keeps on changing , What I need is I need to export both the dataset to a single excelsheet . Both dataset has headers , So i need to export both dataset with header to a single excelsheet using c#. Can anyone help me with a sample code in c#
before u have to create
1. using Excel = Microsoft.Office.Interop.Excel;//in header,and Add correct refference
2. Excel.Application excelHandle1 = PrepareForExport(Ds); //add handle in calling function excelHandle1.Visible = true;
public Excel.Application PrepareForExport(System.Data.DataSet ds,string[] sheet)
{
object missing = System.Reflection.Missing.Value;
Excel.Application excel = new Excel.Application();
Excel.Workbook workbook = excel.Workbooks.Add(missing);
DataTable dt1 = new DataTable();
dt1 = ds.Tables[0];
DataTable dt2 = new DataTable();
dt2 = ds.Tables[1];
Excel.Worksheet newWorksheet;
newWorksheet = (Excel.Worksheet)excel.Worksheets.Add(missing, missing, missing, missing);
newWorksheet.Name ="Name of data sheet";
// for first datatable dt1..
int iCol1 = 0;
foreach (DataColumn c in dt1.Columns)
{
iCol1++;
excel.Cells[1, iCol1] = c.ColumnName;
}
int iRow1 = 0;
foreach (DataRow r in dt1.Rows)
{
iRow1++;
for (int i = 1; i < dt1.Columns.Count + 1; i++)
{
if (iRow1 == 1)
{
// Add the header the first time through
excel.Cells[iRow1, i] = dt1.Columns[i - 1].ColumnName;
}
excel.Cells[iRow1 + 1, i] = r[i - 1].ToString();
}
}
// for second datatable dt2..
int iCol2 = 0;
foreach (DataColumn c in dt2.Columns)
{
iCol2++;
excel.Cells[1, iCol] = c.ColumnName;
}
int iRow2 = 0;
foreach (DataRow r in dt2.Rows)
{
iRow2++;
for (int i = 1; i < dt2.Columns.Count + 1; i++)
{
if (iRow2 == 1)
{
// Add the header the first time through
excel.Cells[iRow2, i] = dt2.Columns[i - 1].ColumnName;
}
excel.Cells[iRow2 + 1, i] = r[i - 1].ToString();
}
}
return excel;
}
First you have to declare namespace:
using Excel = Microsoft.Office.Interop.Excel;
public static void Main(string[] args) {
DataTable dt1 = new DataTable("Employee");
dt1.Columns.Add("Employee ID");
dt1.Columns.Add("Employee Name");
dt1.Rows.Add("1", "ABC");
dt1.Rows.Add("2", "DEF");
dt1.Rows.Add("3", "PQR");
dt1.Rows.Add("4", "XYZ");
DataTable dt3 = new DataTable("Department");
dt3.Columns.Add("Department ID");
dt3.Columns.Add("Department Name");
dt3.Rows.Add("1", "IT");
dt3.Rows.Add("2", "HR");
dt3.Rows.Add("3", "Finance");
DataSet ds = new DataSet();
ds.Tables.Add(dt1);
ds.Tables.Add(dt3);
Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
Excel._Worksheet worksheet = null;
app.Visible = false;
worksheet = workbook.Sheets["Sheet1"];
worksheet = workbook.ActiveSheet;
worksheet.Name = "Exported from gridview";
int z = 1;
for (int x = 0; x < ds.Tables.Count; x++)
{
int r = z;
int t = r + 1;
for (int i = 1; i < ds.Tables[x].Columns.Count + 1; i++)
{
worksheet.Cells[r, i] = ds.Tables[x].Columns[i - 1].Caption;
}
for (int i = 0; i < ds.Tables[x].Rows.Count; i++)
{
for (int j = 0; j < ds.Tables[x].Columns.Count; j++)
{
worksheet.Cells[i + t, j + 1] = ds.Tables[x].Rows[i]
[j].ToString();
}
}
z = ds.Tables[x].Rows.Count + 3;
}
string textPath = "e:\\output.xls";
if (File.Exists(textPath))
{
File.Delete(textPath);
}
workbook.SaveAs(textPath, Type.Missing, Type.Missing, Type.Missing,
Type.Missing,
Type.Missing,
Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive,
Type.Missing, Type.Missing, Type.Missing, Type.Missing);
app.Quit();
}

JComboBox stops responding when focus is directed to another component

I'm having an issue with a small personal application I am puttig together. I am loading data into a JDialog. Within the JDialog, I am loading multiple JPanels that each contain a TableLayout. I am dynamically generating the rows from the data that is loaded into the JDialog. Each row contains a JComboBox and a JTextField that are use to make comments about the status of that particular set of data.
The problem I am encountering has to do with the JComboBox components that are being created. When the JDialog window opens, the JComboBox components are visable and working. Although, as soon as I direct the focus to a different type of component, the JComboBox components stop responding to the mouse clicks.
There is no special logic around the JComboBox components. They simply populate with four different string values, which the user should be able to choose from. No ChangeListener is required for this.
Also note, I wrap all the content in a ScrollPane within the JDialog.
The following is the code where I create the JComboBox components within the TableLayout of the JPanel:
private JPanel createColumnPanel() {
int columnCount = report.getColumns().size();
int rowCount = (columnCount * 2) - 1;
SpringLayout layout = new SpringLayout();
JPanel padding = new JPanel(layout);
TitledBorder border = BorderFactory.createTitledBorder(BorderFactory.createEmptyBorder(), "Column Differences: ");
border.setTitleJustification(TitledBorder.LEFT);
double[] columns = new double[] {3, 75, 3, 175, 3, 150, 3, 100, 3, 125};
double[] rows = new double[rowCount];
for(int i = 0; i < rowCount; i++) {
rows[i] = 20;
if (i + 1 < rowCount)
rows[i + 1] = 5;
i++;
}
double size[][] = {columns, rows};
JPanel panel = new JPanel(new TableLayout(size));
columnStatus = new ArrayList<JComboBox<String>>();
for(int i = 0; i < columnCount; i++) {
JComboBox<String> comboBox = new JComboBox<String>(statusLiterals);
comboBox.setEnabled(true);
columnStatus.add(comboBox);
}
for (int i = 0; i < columnCount; i++) {
panel.add(new JLabel(report.getColumns().get(i).getSchema().toString()), 1 + ", " + (i * 2));
panel.add(new JLabel(report.getColumns().get(i).getTableName()), 3 + ", " + (i * 2));
panel.add(new JLabel(report.getColumns().get(i).getColumnName()), 5 + ", " + (i * 2));
panel.add(columnStatus.get(i), 7 + ", " + (i * 2));
panel.add(new JTextField(report.getColumns().get(i).getRequestor()), 9 + ", " + (i * 2));
}
panel.setBorder(border);
panel.setVisible(true);
panel.setAlignmentX(LEFT_ALIGNMENT);
panel.setBackground(Color.WHITE);
layout.putConstraint(SpringLayout.NORTH, panel, 10, SpringLayout.NORTH, padding);
layout.putConstraint(SpringLayout.SOUTH, padding, 10, SpringLayout.SOUTH, panel);
layout.putConstraint(SpringLayout.EAST, padding, 10, SpringLayout.EAST, panel);
layout.putConstraint(SpringLayout.WEST, panel, 10, SpringLayout.WEST, padding);
padding.add(panel, SwingConstants.CENTER);
padding.setBackground(Color.WHITE);
return padding;
}
The following is the full code for this particular JDialog:
public class ManageRequestsDialog extends JDialog {
private static final long serialVersionUID = 1L;
private ComparisonReport report;
private JPanel outerPanel;
private ScrollPane scrollPane;
private JPanel innerPanel;
private JPanel databasePanel;
private JPanel tablePanel;
private JPanel columnPanel;
private List<JLabel> databaseSchemas = null;
private List<JComboBox<String>> databaseStatus = null;
private List<JTextField> databaseRequestors = null;
private List<JLabel> tableSchemas = null;
private List<JLabel> tableTableNames = null;
private List<JComboBox<String>> tableStatus = null;
private List<JTextField> tableRequestors = null;
private List<JLabel> columnSchemas = null;
private List<JLabel> columnTableNames = null;
private List<JLabel> columnColumnNames = null;
private List<JComboBox<String>> columnStatus = null;
private List<JTextField> columnRequestors = null;
private String[] statusLiterals = DifferenceStatus.getLiterals();
public ManageRequestsDialog (ComparisonReport report) {
super();
this.report = report;
outerPanel = createOuterPanel();
add(outerPanel);
setLayout(new GridLayout(1, 1));
setModal(true);
setSize(700, 500);
setBackground(Color.WHITE);
setResizable(false);
setLocationRelativeTo(null);
setVisible(true);
}
private JPanel createOuterPanel() {
JPanel panel = new JPanel(new GridLayout(1, 1));
scrollPane = createScrollPane();
panel.add(scrollPane);
panel.setVisible(true);
panel.setBackground(Color.WHITE);
return panel;
}
private ScrollPane createScrollPane() {
ScrollPane scrollPane = new ScrollPane();
innerPanel = createInnerPanel();
scrollPane.add(innerPanel);
scrollPane.setVisible(true);
scrollPane.setBackground(Color.WHITE);
return scrollPane;
}
private JPanel createInnerPanel() {
JPanel panel = new JPanel(new BorderLayout());
if (report.getDatabases().size() > 0) {
databasePanel = createDatabasePanel();
panel.add(databasePanel, BorderLayout.NORTH);
}
if (report.getTables().size() > 0) {
tablePanel = createTablePanel();
panel.add(tablePanel, BorderLayout.CENTER);
}
if (report.getColumns().size() > 0) {
columnPanel = createColumnPanel();
panel.add(columnPanel, BorderLayout.SOUTH);
}
panel.setVisible(true);
panel.setBackground(Color.WHITE);
return panel;
}
private JPanel createDatabasePanel() {
int databaseCount = report.getDatabases().size();
int rowCount = (databaseCount * 2) - 1;
SpringLayout layout = new SpringLayout();
JPanel padding = new JPanel(layout);
TitledBorder border = BorderFactory.createTitledBorder(BorderFactory.createEmptyBorder(), "Database Differences: ");
border.setTitleJustification(TitledBorder.LEFT);
double[] columns = new double[] {3, 75, 3, 75, 3, 150};
double[] rows = new double[rowCount];
for(int i = 0; i < rowCount; i++) {
rows[i] = 20;
if (i + 1 < rowCount)
rows[i + 1] = 5;
i++;
}
double size[][] = {columns, rows};
JPanel panel = new JPanel(new TableLayout(size));
databaseStatus = new ArrayList<JComboBox<String>>();
for(int i = 0; i < databaseCount; i++) {
JComboBox<String> comboBox = new JComboBox<String>(statusLiterals);
comboBox.setEnabled(true);
databaseStatus.add(comboBox);
}
for (int i = 0; i < databaseCount; i++) {
panel.add(new JLabel(report.getDatabases().get(i).getSchema().toString()), 1 + ", " + (i * 2));
panel.add(databaseStatus.get(i), 3 + ", " + (i * 2));
panel.add(new JTextField(report.getDatabases().get(i).getRequestor()), 5 + ", " + (i * 2));
}
panel.setBorder(border);
panel.setVisible(true);
panel.setAlignmentX(LEFT_ALIGNMENT);
panel.setBackground(Color.WHITE);
layout.putConstraint(SpringLayout.NORTH, panel, 10, SpringLayout.NORTH, padding);
layout.putConstraint(SpringLayout.SOUTH, padding, 10, SpringLayout.SOUTH, panel);
layout.putConstraint(SpringLayout.EAST, padding, 10, SpringLayout.EAST, panel);
layout.putConstraint(SpringLayout.WEST, panel, 10, SpringLayout.WEST, padding);
padding.add(panel, SwingConstants.CENTER);
padding.setBackground(Color.WHITE);
return padding;
}
private JPanel createTablePanel() {
int tableCount = report.getTables().size();
int rowCount = (tableCount * 2) - 1;
SpringLayout layout = new SpringLayout();
JPanel padding = new JPanel(layout);
TitledBorder border = BorderFactory.createTitledBorder(BorderFactory.createEmptyBorder(), "Table Differences: ");
border.setTitleJustification(TitledBorder.LEFT);
double[] columns = new double[] {3, 75, 3, 175, 3, 100, 3, 150};
double[] rows = new double[rowCount];
for(int i = 0; i < rowCount; i++) {
rows[i] = 20;
if (i + 1 < rowCount)
rows[i + 1] = 5;
i++;
}
double size[][] = {columns, rows};
JPanel panel = new JPanel(new TableLayout(size));
tableStatus = new ArrayList<JComboBox<String>>();
for(int i = 0; i < tableCount; i++) {
JComboBox<String> comboBox = new JComboBox<String>(statusLiterals);
comboBox.setEnabled(true);
tableStatus.add(comboBox);
}
for (int i = 0; i < tableCount; i++) {
panel.add(new JLabel(report.getTables().get(i).getSchema().toString()), 1 + ", " + (i * 2));
panel.add(new JLabel(report.getTables().get(i).getTableName()), 3 + ", " + (i * 2));
panel.add(tableStatus.get(i), 5 + ", " + (i * 2));
panel.add(new JTextField(report.getTables().get(i).getRequestor()), 7 + ", " + (i * 2));
}
panel.setBorder(border);
panel.setVisible(true);
panel.setAlignmentX(LEFT_ALIGNMENT);
panel.setBackground(Color.WHITE);
layout.putConstraint(SpringLayout.NORTH, panel, 10, SpringLayout.NORTH, padding);
layout.putConstraint(SpringLayout.SOUTH, padding, 10, SpringLayout.SOUTH, panel);
layout.putConstraint(SpringLayout.EAST, padding, 10, SpringLayout.EAST, panel);
layout.putConstraint(SpringLayout.WEST, panel, 10, SpringLayout.WEST, padding);
padding.add(panel, SwingConstants.CENTER);
padding.setBackground(Color.WHITE);
return padding;
}
private JPanel createColumnPanel() {
int columnCount = report.getColumns().size();
int rowCount = (columnCount * 2) - 1;
SpringLayout layout = new SpringLayout();
JPanel padding = new JPanel(layout);
TitledBorder border = BorderFactory.createTitledBorder(BorderFactory.createEmptyBorder(), "Column Differences: ");
border.setTitleJustification(TitledBorder.LEFT);
double[] columns = new double[] {3, 75, 3, 175, 3, 150, 3, 100, 3, 125};
double[] rows = new double[rowCount];
for(int i = 0; i < rowCount; i++) {
rows[i] = 20;
if (i + 1 < rowCount)
rows[i + 1] = 5;
i++;
}
double size[][] = {columns, rows};
JPanel panel = new JPanel(new TableLayout(size));
columnStatus = new ArrayList<JComboBox<String>>();
for(int i = 0; i < columnCount; i++) {
JComboBox<String> comboBox = new JComboBox<String>(statusLiterals);
comboBox.setEnabled(true);
columnStatus.add(comboBox);
}
for (int i = 0; i < columnCount; i++) {
panel.add(new JLabel(report.getColumns().get(i).getSchema().toString()), 1 + ", " + (i * 2));
panel.add(new JLabel(report.getColumns().get(i).getTableName()), 3 + ", " + (i * 2));
panel.add(new JLabel(report.getColumns().get(i).getColumnName()), 5 + ", " + (i * 2));
panel.add(columnStatus.get(i), 7 + ", " + (i * 2));
panel.add(new JTextField(report.getColumns().get(i).getRequestor()), 9 + ", " + (i * 2));
}
panel.setBorder(border);
panel.setVisible(true);
panel.setAlignmentX(LEFT_ALIGNMENT);
panel.setBackground(Color.WHITE);
layout.putConstraint(SpringLayout.NORTH, panel, 10, SpringLayout.NORTH, padding);
layout.putConstraint(SpringLayout.SOUTH, padding, 10, SpringLayout.SOUTH, panel);
layout.putConstraint(SpringLayout.EAST, padding, 10, SpringLayout.EAST, panel);
layout.putConstraint(SpringLayout.WEST, panel, 10, SpringLayout.WEST, padding);
padding.add(panel, SwingConstants.CENTER);
padding.setBackground(Color.WHITE);
return padding;
}
}

export to excel in asp.net using openxml

Hello everyone i am working on a project which requires me to export some data to excel on a button click using open xml.Here is the class i am using for exporting to excel:
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml.Drawing.Spreadsheet;
using _14junexcel.Account;
namespace _14junexcel
{
public class CreateExcelOpen
{
public void BuildWorkbook1(string filename)
{
string sFile = #"D:\\ExcelOpenXmlWithImageAndStyles.xlsx";
if (File.Exists(sFile))
{
File.Delete(sFile);
}
BuildWorkbook(sFile);
}
private static void BuildWorkbook(string filename)
{
try
{
using (SpreadsheetDocument xl = SpreadsheetDocument.Create(filename, SpreadsheetDocumentType.Workbook))
{
WorkbookPart wbp = xl.AddWorkbookPart();
WorksheetPart wsp = wbp.AddNewPart<WorksheetPart>();
Workbook wb = new Workbook();
FileVersion fv = new FileVersion();
fv.ApplicationName = "Microsoft Office Excel";
Worksheet ws = new Worksheet();
SheetData sd = new SheetData();
WorkbookStylesPart wbsp = wbp.AddNewPart<WorkbookStylesPart>();
wbsp.Stylesheet = CreateStylesheet();
wbsp.Stylesheet.Save();
string sImagePath = #"C:\\Users\\Public\\Pictures\\Sample Pictures\\Jellyfish.jpg";
DrawingsPart dp = wsp.AddNewPart<DrawingsPart>();
ImagePart imgp = dp.AddImagePart(ImagePartType.Png, wsp.GetIdOfPart(dp));
using (FileStream fs = new FileStream(sImagePath, FileMode.Open))
{
imgp.FeedData(fs);
}
NonVisualDrawingProperties nvdp = new NonVisualDrawingProperties();
nvdp.Id = 1025;
nvdp.Name = "Picture 1";
nvdp.Description = "polymathlogo";
DocumentFormat.OpenXml.Drawing.PictureLocks picLocks = new DocumentFormat.OpenXml.Drawing.PictureLocks();
picLocks.NoChangeAspect = true;
picLocks.NoChangeArrowheads = true;
NonVisualPictureDrawingProperties nvpdp = new NonVisualPictureDrawingProperties();
nvpdp.PictureLocks = picLocks;
NonVisualPictureProperties nvpp = new NonVisualPictureProperties();
nvpp.NonVisualDrawingProperties = nvdp;
nvpp.NonVisualPictureDrawingProperties = nvpdp;
DocumentFormat.OpenXml.Drawing.Stretch stretch = new DocumentFormat.OpenXml.Drawing.Stretch();
stretch.FillRectangle = new DocumentFormat.OpenXml.Drawing.FillRectangle();
BlipFill blipFill = new BlipFill();
DocumentFormat.OpenXml.Drawing.Blip blip = new DocumentFormat.OpenXml.Drawing.Blip();
blip.Embed = dp.GetIdOfPart(imgp);
blip.CompressionState = DocumentFormat.OpenXml.Drawing.BlipCompressionValues.Print;
blipFill.Blip = blip;
blipFill.SourceRectangle = new DocumentFormat.OpenXml.Drawing.SourceRectangle();
blipFill.Append(stretch);
DocumentFormat.OpenXml.Drawing.Transform2D t2d = new DocumentFormat.OpenXml.Drawing.Transform2D();
DocumentFormat.OpenXml.Drawing.Offset offset = new DocumentFormat.OpenXml.Drawing.Offset();
offset.X = 0;
offset.Y = 0;
t2d.Offset = offset;
Bitmap bm = new Bitmap(sImagePath);
//http://en.wikipedia.org/wiki/English_Metric_Unit#DrawingML
//http://stackoverflow.com/questions/1341930/pixel-to-centimeter
//http://stackoverflow.com/questions/139655/how-to-convert-pixels-to-points-px-to-pt-in-net-c
DocumentFormat.OpenXml.Drawing.Extents extents = new DocumentFormat.OpenXml.Drawing.Extents();
extents.Cx = (long)bm.Width * (long)((float)0 / bm.HorizontalResolution);
extents.Cy = (long)bm.Height * (long)((float)0 / bm.VerticalResolution);
bm.Dispose();
t2d.Extents = extents;
ShapeProperties sp = new ShapeProperties();
sp.BlackWhiteMode = DocumentFormat.OpenXml.Drawing.BlackWhiteModeValues.Auto;
sp.Transform2D = t2d;
DocumentFormat.OpenXml.Drawing.PresetGeometry prstGeom = new DocumentFormat.OpenXml.Drawing.PresetGeometry();
prstGeom.Preset = DocumentFormat.OpenXml.Drawing.ShapeTypeValues.Rectangle;
prstGeom.AdjustValueList = new DocumentFormat.OpenXml.Drawing.AdjustValueList();
sp.Append(prstGeom);
sp.Append(new DocumentFormat.OpenXml.Drawing.NoFill());
DocumentFormat.OpenXml.Drawing.Spreadsheet.Picture picture = new DocumentFormat.OpenXml.Drawing.Spreadsheet.Picture();
picture.NonVisualPictureProperties = nvpp;
picture.BlipFill = blipFill;
picture.ShapeProperties = sp;
Position pos = new Position();
pos.X = 0;
pos.Y = 0;
Extent ext = new Extent();
ext.Cx = extents.Cx;
ext.Cy = extents.Cy;
AbsoluteAnchor anchor = new AbsoluteAnchor();
anchor.Position = pos;
anchor.Extent = ext;
anchor.Append(picture);
anchor.Append(new ClientData());
WorksheetDrawing wsd = new WorksheetDrawing();
wsd.Append(anchor);
Drawing drawing = new Drawing();
drawing.Id = dp.GetIdOfPart(imgp);
wsd.Save(dp);
UInt32 index;
Random rand = new Random();
sd.Append(CreateHeader(2));
sd.Append(CreateColumnHeader(4));
for (index = 5; index < 6; ++index)
{
sd.Append(CreateContent(index, ref rand));
}
ws.Append(sd);
ws.Append(drawing);
wsp.Worksheet = ws;
wsp.Worksheet.Save();
Sheets sheets = new Sheets();
Sheet sheet = new Sheet();
sheet.Name = "Sheet1";
sheet.SheetId = 1;
sheet.Id = wbp.GetIdOfPart(wsp);
sheets.Append(sheet);
wb.Append(fv);
wb.Append(sheets);
xl.WorkbookPart.Workbook = wb;
xl.WorkbookPart.Workbook.Save();
//xl.WorkbookPart.Workbook.Save();
xl.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
Console.ReadLine();
}
}
private static Stylesheet CreateStylesheet()
{
Stylesheet ss = new Stylesheet();
Fonts fts = new Fonts();
DocumentFormat.OpenXml.Spreadsheet.Font ft = new DocumentFormat.OpenXml.Spreadsheet.Font();
FontName ftn = new FontName();
ftn.Val = StringValue.FromString("Calibri");
FontSize ftsz = new FontSize();
ftsz.Val = DoubleValue.FromDouble(11);
ft.FontName = ftn;
ft.FontSize = ftsz;
fts.Append(ft);
ft = new DocumentFormat.OpenXml.Spreadsheet.Font();
ftn = new FontName();
ftn.Val = StringValue.FromString("Palatino Linotype");
ftsz = new FontSize();
ftsz.Val = DoubleValue.FromDouble(18);
ft.FontName = ftn;
ft.FontSize = ftsz;
fts.Append(ft);
fts.Count = UInt32Value.FromUInt32((uint)fts.ChildElements.Count);
Fills fills = new Fills();
Fill fill;
PatternFill patternFill;
fill = new Fill();
patternFill = new PatternFill();
patternFill.PatternType = PatternValues.None;
fill.PatternFill = patternFill;
fills.Append(fill);
fill = new Fill();
patternFill = new PatternFill();
patternFill.PatternType = PatternValues.Gray125;
fill.PatternFill = patternFill;
fills.Append(fill);
fill = new Fill();
patternFill = new PatternFill();
patternFill.PatternType = PatternValues.Solid;
patternFill.ForegroundColor = new ForegroundColor();
patternFill.ForegroundColor.Rgb = HexBinaryValue.FromString("00ff9728");
patternFill.BackgroundColor = new BackgroundColor();
patternFill.BackgroundColor.Rgb = patternFill.ForegroundColor.Rgb;
fill.PatternFill = patternFill;
fills.Append(fill);
fills.Count = UInt32Value.FromUInt32((uint)fills.ChildElements.Count);
Borders borders = new Borders();
Border border = new Border();
border.LeftBorder = new LeftBorder();
border.RightBorder = new RightBorder();
border.TopBorder = new TopBorder();
border.BottomBorder = new BottomBorder();
border.DiagonalBorder = new DiagonalBorder();
borders.Append(border);
border = new Border();
border.LeftBorder = new LeftBorder();
border.LeftBorder.Style = BorderStyleValues.Thin;
border.RightBorder = new RightBorder();
border.RightBorder.Style = BorderStyleValues.Thin;
border.TopBorder = new TopBorder();
border.TopBorder.Style = BorderStyleValues.Thin;
border.BottomBorder = new BottomBorder();
border.BottomBorder.Style = BorderStyleValues.Thin;
border.DiagonalBorder = new DiagonalBorder();
borders.Append(border);
borders.Count = UInt32Value.FromUInt32((uint)borders.ChildElements.Count);
CellStyleFormats csfs = new CellStyleFormats();
CellFormat cf = new CellFormat();
cf.NumberFormatId = 0;
cf.FontId = 0;
cf.FillId = 0;
cf.BorderId = 1;
csfs.Append(cf);
csfs.Count = UInt32Value.FromUInt32((uint)csfs.ChildElements.Count);
uint iExcelIndex = 164;
NumberingFormats nfs = new NumberingFormats();
CellFormats cfs = new CellFormats();
cf = new CellFormat();
cf.NumberFormatId = 0;
cf.FontId = 0;
cf.FillId = 0;
cf.BorderId = 0;
cf.FormatId = 0;
cfs.Append(cf);
NumberingFormat nfDateTime = new NumberingFormat();
nfDateTime.NumberFormatId = UInt32Value.FromUInt32(iExcelIndex++);
nfDateTime.FormatCode = StringValue.FromString("dd/mm/yyyy hh:mm:ss");
nfs.Append(nfDateTime);
NumberingFormat nf4decimal = new NumberingFormat();
nf4decimal.NumberFormatId = UInt32Value.FromUInt32(iExcelIndex++);
nf4decimal.FormatCode = StringValue.FromString("#,##0.0000");
nfs.Append(nf4decimal);
// #,##0.00 is also Excel style index 4
NumberingFormat nf2decimal = new NumberingFormat();
nf2decimal.NumberFormatId = UInt32Value.FromUInt32(iExcelIndex++);
nf2decimal.FormatCode = StringValue.FromString("#,##0.00");
nfs.Append(nf2decimal);
// # is also Excel style index 49
NumberingFormat nfForcedText = new NumberingFormat();
nfForcedText.NumberFormatId = UInt32Value.FromUInt32(iExcelIndex++);
nfForcedText.FormatCode = StringValue.FromString("#");
nfs.Append(nfForcedText);
//Alignment
Alignment align = new Alignment(){Horizontal = HorizontalAlignmentValues.General,Vertical=VerticalAlignmentValues.Center};
//wraptext
// Alignment align1 = new Alignment(){Horizontal=HorizontalAlignmentValues.CenterContinuous,Vertical=VerticalAlignmentValues.Center};
// index 1
cf = new CellFormat();
cf.NumberFormatId = nfDateTime.NumberFormatId;
cf.FontId = 0;
cf.FillId = 0;
cf.BorderId = 1;
cf.FormatId = 0;
cf.ApplyNumberFormat = BooleanValue.FromBoolean(true);
cfs.Append(cf);
// index 2
cf = new CellFormat();
cf.NumberFormatId = nf4decimal.NumberFormatId;
cf.FontId = 0;
cf.FillId = 0;
cf.BorderId = 1;
cf.FormatId = 0;
cf.ApplyNumberFormat = BooleanValue.FromBoolean(true);
cfs.Append(cf);
// index 3
cf = new CellFormat();
cf.NumberFormatId = nf2decimal.NumberFormatId;
cf.FontId = 0;
cf.FillId = 0;
cf.BorderId = 1;
cf.FormatId = 0;
cf.ApplyNumberFormat = BooleanValue.FromBoolean(true);
cfs.Append(cf);
// index 4
cf = new CellFormat();
cf.NumberFormatId = nfForcedText.NumberFormatId;
cf.FontId = 0;
cf.FillId = 0;
cf.BorderId = 1;
cf.FormatId = 0;
cf.ApplyNumberFormat = BooleanValue.FromBoolean(true);
cfs.Append(cf);
// index 5
// Header text
cf = new CellFormat();
cf.NumberFormatId = nfForcedText.NumberFormatId;
cf.FontId = 1;
cf.FillId = 0;
cf.BorderId = 0;
cf.FormatId = 0;
cf.ApplyNumberFormat = BooleanValue.FromBoolean(true);
cfs.Append(cf);
// index 6
// column text
cf = new CellFormat();
cf.NumberFormatId = nfForcedText.NumberFormatId;
cf.FontId = 1;
cf.FillId = 1;
cf.BorderId = 1;
cf.FormatId = 1;
cf.ApplyNumberFormat = BooleanValue.FromBoolean(true);
cfs.Append(cf);
// index 7
// coloured 2 decimal text
cf = new CellFormat();
cf.NumberFormatId = nf2decimal.NumberFormatId;
cf.FontId = 0;
//cf.FillId = 2;
cf.FillId = 0;
cf.BorderId = 1;
cf.FormatId =0;
cf.ApplyNumberFormat = BooleanValue.FromBoolean(true);
cfs.Append(cf);
//cf.Append(align);
cf.Append(align);
// index 8
// coloured column text
cf = new CellFormat();
cf.NumberFormatId = nfForcedText.NumberFormatId;
cf.FontId = 0;
//cf.FillId = 2;
cf.FillId = 0;
cf.BorderId = 1;
cf.FormatId = 0;
cf.ApplyNumberFormat = BooleanValue.FromBoolean(true);
cfs.Append(cf);
nfs.Count = UInt32Value.FromUInt32((uint)nfs.ChildElements.Count);
cfs.Count = UInt32Value.FromUInt32((uint)cfs.ChildElements.Count);
ss.Append(nfs);
ss.Append(fts);
ss.Append(fills);
ss.Append(borders);
ss.Append(csfs);
ss.Append(cfs);
CellStyles css = new CellStyles();
CellStyle cs = new CellStyle();
cs.Name = StringValue.FromString("Normal");
cs.FormatId = 0;
cs.BuiltinId = 0;
css.Append(cs);
css.Count = UInt32Value.FromUInt32((uint)css.ChildElements.Count);
ss.Append(css);
DifferentialFormats dfs = new DifferentialFormats();
dfs.Count = 0;
ss.Append(dfs);
TableStyles tss = new TableStyles();
tss.Count = 0;
tss.DefaultTableStyle = StringValue.FromString("TableStyleMedium9");
tss.DefaultPivotStyle = StringValue.FromString("PivotStyleLight16");
ss.Append(tss);
return ss;
}
private static Row CreateHeader(UInt32 index)
{
Row r = new Row();
r.RowIndex = index;
Cell c = new Cell();
c.DataType = CellValues.String;
c.StyleIndex = 5;
c.CellReference = "A" + index.ToString();
c.CellValue = new CellValue("REPORT");
r.Append(c);
return r;
}
private static Row CreateColumnHeader(UInt32 index)
{
Row r = new Row();
r.RowIndex = index;
Cell c;
c = new Cell();
c.DataType = CellValues.String;
c.StyleIndex = 7;
c.CellReference = "A" + index.ToString();
c.CellValue = new CellValue("Retail Customer Group");
r.Append(c);
c = new Cell();
c.DataType = CellValues.String;
c.StyleIndex = 7;
c.CellReference = "B" + index.ToString();
c.CellValue = new CellValue("Product Promotion Group");
r.Append(c);
return r;
}
private static Row CreateContent(UInt32 index, ref Random rd)
{
Row r = new Row();
r.RowIndex = index;
Cell c;
c = new Cell();
c.StyleIndex = 7;
c.CellReference = "A" + index.ToString();
//c.CellValue = new CellValue(rd.Next(1000000000).ToString());
c.CellValue = new CellValue("12334");
r.Append(c);
DateTime dtEpoch = new DateTime(1900, 1, 1, 0, 0, 0, 0);
DateTime dt = dtEpoch.AddDays(rd.NextDouble() * 100000.0);
TimeSpan ts = dt - dtEpoch;
double fExcelDateTime;
// Excel has "bug" of treating 29 Feb 1900 as valid
// 29 Feb 1900 is 59 days after 1 Jan 1900, so just skip to 1 Mar 1900
if (ts.Days >= 59)
{
fExcelDateTime = ts.TotalDays + 2.0;
}
else
{
fExcelDateTime = ts.TotalDays + 1.0;
}
c = new Cell();
c.StyleIndex = 7;
c.CellReference = "B" + index.ToString();
c.CellValue = new CellValue("124515");
//c.CellValue = new CellValue(fExcelDateTime.ToString());
r.Append(c);
return r;
}
}
}
and this is the function for button click :
protected void Button1_Click(object sender, EventArgs e)
{
string qwe = TextBox1.Text;
string ert = TextBox2.Text;
string filename = #"D:\\ExcelOpenXmlWithImageAndStyles.xlsx";
CreateExcelOpen exp = new CreateExcelOpen();
exp.BuildWorkbook1(filename);
}
here are my requirements:
1.I need to pass the values of two textboxes to the two cells(which now contain values 12334 and 124515).
2. The heading column does not adjust itself to accomodate the values which i have provided(Retail customer group etc).Please suggest the
modifications required in this class to enable the autofit.
Thank you.
In Your CreateContent method you have hard coded values like:
c.CellValue = new CellValue("12334");
change it with values of text boxes that you want to show.
for setting width of headers, you will have to add columns along with Cells as you need columns to define the width, following article will be of some help for you:
http://catalog.codeproject.com/script/Articles/ArticleVersion.aspx?aid=371203&av=543408
I wrote my own export to Excel writer. It is fast and allows for substantial formatting of the cells. You can review it at
https://openxmlexporttoexcel.codeplex.com/
I hope it helps.
I've spent a lot of time googling OpenXml related questions.
I finally found a solution to my problems by combining OpenXml features with Excel VBA.
So,
I have Excel - macro enabled file (xlsm) as template for my project.
Whatever logic is hard to implement in OpenXml I moved to VBA.
For AutoFit for example it is as easy as:
Sub Workbook_Open()
ActiveSheet.Columns.AutoFit
End Sub
Hope it may help.

Resources