XSSF Apache POI XSSFCellStyle - xssf

Rotating column heading using HSSFCellStyle using method setRotation working fine as below program ---
public static void main(String[] args)throws Exception
{
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet spreadsheet = workbook.createSheet(
"Text direction");
HSSFRow row = spreadsheet.createRow(2);
HSSFCellStyle myStyle = workbook.createCellStyle();
myStyle.setRotation((short) 0);
HSSFCell cell = row.createCell(1);
cell.setCellValue("0D angle");
cell.setCellStyle(myStyle);
myStyle=workbook.createCellStyle();
myStyle.setRotation((short) 90);
cell = row.createCell(3);
cell.setCellValue("30D angle");
cell.setCellStyle(myStyle);
myStyle=workbook.createCellStyle();
myStyle.setRotation((short) -90);
cell = row.createCell(5);
cell.setCellValue("90D angle");
cell.setCellStyle(myStyle);
FileOutputStream out = new FileOutputStream(
new File("textdirection.xlsx"));
workbook.write(out);
out.close();
System.out.println(
"textdirection.xlsx written successfully");
}
but same code writen using XSSF output file column header not rotating.
below code using XSSF--
public static void main(String[] args)throws Exception
{
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet spreadsheet = workbook.createSheet(
"Text direction");
XSSFRow row = spreadsheet.createRow(2);
XSSFCellStyle myStyle = workbook.createCellStyle();
myStyle.setRotation((short) 0);
XSSFCell cell = row.createCell(1);
cell.setCellValue("0D angle");
cell.setCellStyle(myStyle);
myStyle=workbook.createCellStyle();
myStyle.setRotation((short) 180);
cell = row.createCell(3);
cell.setCellValue("30D angle");
cell.setCellStyle(myStyle);
myStyle=workbook.createCellStyle();
myStyle.setRotation((short) -180);
cell = row.createCell(5);
cell.setCellValue("90D angle");
cell.setCellStyle(myStyle);
FileOutputStream out = new FileOutputStream(
new File("textdirection.xlsx"));
workbook.write(out);
out.close();
System.out.println(
"textdirection.xlsx written successfully");
}
so can any one give me hint on this.
Thanks.

It's all about formats for XLS and XLSX sheets and workbooks - they are different.
Here's part of JavaDoc on setRotation() method:
public void setRotation(short rotation)
Set the degree of rotation for the text in the cell
Expressed in degrees. Values range from 0 to 180. The first letter of
the text is considered the center-point of the arc. For 0 - 90, the
value represents degrees above horizon. For 91-180 the degrees below
the horizon is calculated as: [degrees below horizon] = 90 -
textRotation.
Note: HSSF uses values from -90 to 90 degrees, whereas
XSSF uses values from 0 to 180 degrees. The implementations of this
method will map between these two value-ranges accordingly, however
the corresponding getter is returning values in the range mandated by
the current type of Excel file-format that this CellStyle is applied
to.
So, here's the correct example of what you're willing to do:
package com.github.xsavikx.apachepoitest;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class ApachePOITest {
public static void main(String[] args) throws Exception {
XSSF();
HSSF();
}
private static void XSSF() throws IOException {
String filename = "textdirection_xssf.xlsx";
try (XSSFWorkbook workbook = new XSSFWorkbook();
FileOutputStream out = new FileOutputStream(new File(filename));) {
XSSFSheet spreadsheet = workbook.createSheet(
"Text direction");
XSSFRow row = spreadsheet.createRow(2);
XSSFCellStyle myStyle = workbook.createCellStyle();
myStyle.setRotation((short) 0);
XSSFCell cell = row.createCell(1);
cell.setCellValue("0D angle");
cell.setCellStyle(myStyle);
myStyle = workbook.createCellStyle();
myStyle.setRotation((short) 90);
cell = row.createCell(3);
cell.setCellValue("30D angle");
cell.setCellStyle(myStyle);
myStyle = workbook.createCellStyle();
myStyle.setRotation((short) 180);
cell = row.createCell(5);
cell.setCellValue("90D angle");
cell.setCellStyle(myStyle);
workbook.write(out);
System.out.println(String.format("%s written successfully", filename));
}
}
private static void HSSF() throws IOException {
String filename = "textdirection_hssf.xls";
try (HSSFWorkbook workbook = new HSSFWorkbook();
FileOutputStream out = new FileOutputStream(new File(filename));) {
HSSFSheet spreadsheet = workbook.createSheet(
"Text direction");
HSSFRow row = spreadsheet.createRow(2);
HSSFCellStyle myStyle = workbook.createCellStyle();
myStyle.setRotation((short) 0);
HSSFCell cell = row.createCell(1);
cell.setCellValue("0D angle");
cell.setCellStyle(myStyle);
myStyle = workbook.createCellStyle();
myStyle.setRotation((short) 90);
cell = row.createCell(3);
cell.setCellValue("30D angle");
cell.setCellStyle(myStyle);
myStyle = workbook.createCellStyle();
myStyle.setRotation((short) -90);
cell = row.createCell(5);
cell.setCellValue("90D angle");
cell.setCellStyle(myStyle);
workbook.write(out);
System.out.println(String.format("%s written successfully", filename));
}
}
}

Related

Cell formatting issue in dynamic table created with OpenXml 2.7 Wordprocessing

First I have created table manually using MS Word 2010. And then I inspected that table using Open Xml Productivity tool and used the reflected code to generate dynamic table with same cell formattings using C#.
But when the Table is generated, there is a white space at the bottom of every cell.
After increased the row height using MS Word 2010
And I even tried the basic example here Add tables to word processing documents (Open XML SDK). but the same result. Any solution to get rid of this white line ?
Please share your code. I think only for the first column its is adding.
MSDN examples are not adding any white space at the bottom of every cell.
try to copy paste the below code in your solution. This is msdn example
using System.Collections.Generic;
using System.IO;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using A = DocumentFormat.OpenXml.Drawing;
using DW = DocumentFormat.OpenXml.Drawing.Wordprocessing;
using PIC = DocumentFormat.OpenXml.Drawing.Pictures;
namespace word
{
class Program
{
static void Main(string[] args)
{
//Console.WriteLine("Hello World!");
// CreateWordprocessingDocument(#"D:\data\word.docx");
//string document = #"D:\data\pic1.docx";
//string fileName = #"D:\data\Capture.JPG";
//InsertAPicture(document, fileName);
string fileName = #"D:\data\Table7.docx";
CreateTable2(fileName);
}
public static void CreateTable2(string fileName)
{
using (WordprocessingDocument wordDocument =
WordprocessingDocument.Create(fileName, WordprocessingDocumentType.Document))
{
MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
mainPart.Document = new Document();
Body body = mainPart.Document.AppendChild(new Body());
body.AppendChild(para1("4.1 Process"));
// Create a table.
Table tbl = new Table();
tbl.AppendChild(tablestyle());
// Add 3 columns to the table.
TableGrid tg = new TableGrid(new GridColumn(), new GridColumn(), new GridColumn(), new GridColumn(), new GridColumn());
tbl.AppendChild(tg);
// Add row to the table.
tbl.AppendChild(templaterow());
string[] items = { "Mike Gold", "Don Box",
"Sundar Lal", "Neel Beniwal","123" };
List<string> authorsRange = new List<string>(items);
tbl.AppendChild(rowcolumns(authorsRange));
body.AppendChild(tbl);
}
}
public static void CreateTable1(string fileName)
{
using (WordprocessingDocument wordDocument =
WordprocessingDocument.Create(fileName, WordprocessingDocumentType.Document))
{
wordDocument.AddMainDocumentPart();
// siga a ordem
Document doc = new Document();
Body body = new Body();
// 1 paragrafo
Paragraph para = new Paragraph();
ParagraphProperties paragraphProperties1 = new ParagraphProperties();
ParagraphStyleId paragraphStyleId1 = new ParagraphStyleId() { Val = "Normal" };
Justification justification1 = new Justification() { Val = JustificationValues.Left };
ParagraphMarkRunProperties paragraphMarkRunProperties1 = new ParagraphMarkRunProperties();
paragraphProperties1.Append(paragraphStyleId1);
paragraphProperties1.Append(justification1);
paragraphProperties1.Append(paragraphMarkRunProperties1);
Run run = new Run();
RunProperties runProperties1 = new RunProperties();
Text text = new Text() { Text = "4. Process Details" };
// siga a ordem
run.Append(runProperties1);
run.Append(text);
para.Append(paragraphProperties1);
para.Append(run);
// 2 paragrafo
Paragraph para2 = new Paragraph();
ParagraphProperties paragraphProperties2 = new ParagraphProperties();
ParagraphStyleId paragraphStyleId2 = new ParagraphStyleId() { Val = "Heading1" };
Justification justification2 = new Justification() { Val = JustificationValues.Start };
ParagraphMarkRunProperties paragraphMarkRunProperties2 = new ParagraphMarkRunProperties();
paragraphProperties2.Append(paragraphStyleId2);
paragraphProperties2.Append(justification2);
paragraphProperties2.Append(paragraphMarkRunProperties2);
Run run2 = new Run();
Text text2 = new Text() { Text = "4.1 Process Maps" };
//text2.Text = "4.1 Process Maps";
run2.AppendChild(text2);
para2.Append(paragraphProperties2);
para2.Append(run2);
//Para2
Paragraph para3 = new Paragraph();
ParagraphProperties paragraphProperties3 = new ParagraphProperties();
ParagraphStyleId paragraphStyleId3 = new ParagraphStyleId() { Val = "Heading2" };
Justification justification3 = new Justification() { Val = JustificationValues.Start };
ParagraphMarkRunProperties paragraphMarkRunProperties3 = new ParagraphMarkRunProperties();
paragraphProperties3.Append(paragraphStyleId3);
paragraphProperties3.Append(justification3);
paragraphProperties3.Append(paragraphMarkRunProperties3);
Run run3 = new Run();
Text text3 = new Text() { Text = "4.2 Process Steps" };
//Text text3 = new Text();
//text3.Text = "4.2 Process Steps";
run3.AppendChild(text3);
para3.Append(paragraphProperties3);
para3.Append(run3);
////////////////////////////////////////////////////////////////////
// Create a table.
Table tbl = new Table();
// Set the style and width for the table.
TableProperties tableProp = new TableProperties();
TableStyle tableStyle = new TableStyle() { Val = "TableGrid" };
// Make the table width 100% of the page width.
TableWidth tableWidth = new TableWidth() { Width = "5000", Type = TableWidthUnitValues.Pct };
//// Create Table Borders
TableBorders tblBorders = new TableBorders();
TopBorder topBorder = new TopBorder();
topBorder.Val = new EnumValue<BorderValues>(BorderValues.Thick);
topBorder.Color = "CC0000";
tblBorders.AppendChild(topBorder);
BottomBorder bottomBorder = new BottomBorder();
bottomBorder.Val = new EnumValue<BorderValues>(BorderValues.Thick);
bottomBorder.Color = "CC0000";
tblBorders.AppendChild(bottomBorder);
RightBorder rightBorder = new RightBorder();
rightBorder.Val = new EnumValue<BorderValues>(BorderValues.Thick);
rightBorder.Color = "CC0000";
tblBorders.AppendChild(rightBorder);
LeftBorder leftBorder = new LeftBorder();
leftBorder.Val = new EnumValue<BorderValues>(BorderValues.Thick);
leftBorder.Color = "CC0000";
tblBorders.AppendChild(leftBorder);
InsideHorizontalBorder insideHBorder = new InsideHorizontalBorder();
insideHBorder.Val = new EnumValue<BorderValues>(BorderValues.Thick);
insideHBorder.Color = "CC0000";
tblBorders.AppendChild(insideHBorder);
InsideVerticalBorder insideVBorder = new InsideVerticalBorder();
insideVBorder.Val = new EnumValue<BorderValues>(BorderValues.Thick);
insideVBorder.Color = "CC0000";
tblBorders.AppendChild(insideVBorder);
//// Add the table borders to the properties
tableProp.AppendChild(tblBorders);
// Apply
tableProp.Append(tableStyle, tableWidth);
tbl.AppendChild(tableProp);
// Add 3 columns to the table.
TableGrid tg = new TableGrid(new GridColumn(), new GridColumn(), new GridColumn(), new GridColumn(), new GridColumn());
tbl.AppendChild(tg);
// Create 1 row to the table.
TableRow tr1 = new TableRow();
// Add a cell to each column in the row.
TableCell tc1 = new TableCell(new Paragraph(new Run(new Text("Step"))));
TableCell tc2 = new TableCell(new Paragraph(new Run(new Text("SubStep"))));
TableCell tc3 = new TableCell(new Paragraph(new Run(new Text("Group"))));
TableCell tc4 = new TableCell(new Paragraph(new Run(new Text("Description"))));
TableCell tc5 = new TableCell(new Paragraph(new Run(new Text("ScreenShot"))));
tr1.Append(tc1, tc2, tc3, tc4, tc5);
// Add row to the table.
tbl.AppendChild(tr1);
// Add the table to the document
body.Append(para);
body.Append(para2);
body.Append(para3);
body.AppendChild(tbl);
doc.Append(body);
wordDocument.MainDocumentPart.Document = doc;
wordDocument.Save();
wordDocument.Close();
}
}
public static void CreateTable(string fileName)
{
// Use the file name and path passed in as an argument
// to open an existing Word 2007 document.
// Create a document by supplying the filepath.
using (WordprocessingDocument wordDocument =
WordprocessingDocument.Create(fileName, WordprocessingDocumentType.Document))
{
// Add a main document part.
MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
// Create the document structure and add some text.
mainPart.Document = new Document();
Body body = mainPart.Document.AppendChild(new Body());
// Create an empty table.
Table table = new Table();
// Create a TableProperties object and specify its border information.
TableProperties tblProp = new TableProperties(
new TableBorders(
new TopBorder()
{
Val =
new EnumValue<BorderValues>(BorderValues.Dashed),
Size = 24
},
new BottomBorder()
{
Val =
new EnumValue<BorderValues>(BorderValues.Dashed),
Size = 24
},
new LeftBorder()
{
Val =
new EnumValue<BorderValues>(BorderValues.Dashed),
Size = 24
},
new RightBorder()
{
Val =
new EnumValue<BorderValues>(BorderValues.Dashed),
Size = 24
},
new InsideHorizontalBorder()
{
Val =
new EnumValue<BorderValues>(BorderValues.Dashed),
Size = 24
},
new InsideVerticalBorder()
{
Val =
new EnumValue<BorderValues>(BorderValues.Dashed),
Size = 24
}
)
);
// Append the TableProperties object to the empty table.
table.AppendChild<TableProperties>(tblProp);
// Create a row.
TableRow tr = new TableRow();
// Create a cell.
TableCell tc1 = new TableCell();
// Specify the width property of the table cell.
tc1.Append(new TableCellProperties(
new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2400" }));
// Specify the table cell content.
tc1.Append(new Paragraph(new Run(new Text("some text"))));
// Append the table cell to the table row.
tr.Append(tc1);
// Create a second table cell by copying the OuterXml value of the first table cell.
TableCell tc2 = new TableCell(tc1.OuterXml);
// Append the table cell to the table row.
tr.Append(tc2);
// Append the table row to the table.
table.Append(tr);
// Append the table to the document.
//doc.MainDocumentPart.Document.Body.Append(table);
body.Append(table);
}
}
public static void CreateWordprocessingDocument(string filepath)
{
// Create a document by supplying the filepath.
using (WordprocessingDocument wordDocument =
WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document))
{
// Add a main document part.
MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
// Create the document structure and add some text.
mainPart.Document = new Document();
Body body = mainPart.Document.AppendChild(new Body());
body.AppendChild(paragraph("12345"));
}
}
public static Paragraph para1(string txt)
{
// 1 paragrafo
Paragraph para = new Paragraph();
ParagraphProperties paragraphProperties1 = new ParagraphProperties();
ParagraphStyleId paragraphStyleId1 = new ParagraphStyleId() { Val = "Normal" };
Justification justification1 = new Justification() { Val = JustificationValues.Left };
ParagraphMarkRunProperties paragraphMarkRunProperties1 = new ParagraphMarkRunProperties();
paragraphProperties1.Append(paragraphStyleId1);
paragraphProperties1.Append(justification1);
paragraphProperties1.Append(paragraphMarkRunProperties1);
Run run = para.AppendChild(new Run());
run.AppendChild(new Text(txt));
//para.Append(paragraphProperties1);
//para.Append(run);
return para;
}
public static TableProperties tablestyle()
{
// Set the style and width for the table.
TableProperties tableProp = new TableProperties();
TableStyle tableStyle = new TableStyle() { Val = "TableGrid" };
// Make the table width 100% of the page width.
TableWidth tableWidth = new TableWidth() { Width = "5000", Type = TableWidthUnitValues.Pct };
//// Create Table Borders
TableBorders tblBorders = new TableBorders();
TopBorder topBorder = new TopBorder();
topBorder.Val = new EnumValue<BorderValues>(BorderValues.Thick);
topBorder.Color = "CC0000";
tblBorders.AppendChild(topBorder);
BottomBorder bottomBorder = new BottomBorder();
bottomBorder.Val = new EnumValue<BorderValues>(BorderValues.Thick);
bottomBorder.Color = "CC0000";
tblBorders.AppendChild(bottomBorder);
RightBorder rightBorder = new RightBorder();
rightBorder.Val = new EnumValue<BorderValues>(BorderValues.Thick);
rightBorder.Color = "CC0000";
tblBorders.AppendChild(rightBorder);
LeftBorder leftBorder = new LeftBorder();
leftBorder.Val = new EnumValue<BorderValues>(BorderValues.Thick);
leftBorder.Color = "CC0000";
tblBorders.AppendChild(leftBorder);
InsideHorizontalBorder insideHBorder = new InsideHorizontalBorder();
insideHBorder.Val = new EnumValue<BorderValues>(BorderValues.Thick);
insideHBorder.Color = "CC0000";
tblBorders.AppendChild(insideHBorder);
InsideVerticalBorder insideVBorder = new InsideVerticalBorder();
insideVBorder.Val = new EnumValue<BorderValues>(BorderValues.Thick);
insideVBorder.Color = "CC0000";
tblBorders.AppendChild(insideVBorder);
//// Add the table borders to the properties
tableProp.AppendChild(tblBorders);
// Apply
tableProp.Append(tableStyle, tableWidth);
return tableProp;
}
public static TableRow templaterow()
{
// Create 1 row to the table.
TableRow tr1 = new TableRow();
// Add a cell to each column in the row.
TableCell tc1 = new TableCell(new Paragraph(new Run(new Text("Step"))));
TableCellProperties tcr1 = new TableCellProperties();
var shading = new Shading()
{
Color = "auto",
Fill = "B4C6E7",
Val = ShadingPatternValues.Clear
};
tcr1.Append(shading);
tc1.Append(tcr1);
TableCell tc2 = new TableCell(new Paragraph(new Run(new Text("SubStep"))));
TableCell tc3 = new TableCell(new Paragraph(new Run(new Text("Group"))));
TableCell tc4 = new TableCell(new Paragraph(new Run(new Text("Description"))));
TableCell tc5 = new TableCell(new Paragraph(new Run(new Text("ScreenShot"))));
TableCellProperties tcr2 = new TableCellProperties();
var shading2 = new Shading()
{
Color = "auto",
Fill = "B4C6E7",
Val = ShadingPatternValues.Clear
};
tcr2.Append(shading2);
tc2.Append(tcr2);
//tc2.Append(tcr1);
tr1.Append(tc1, tc2, tc3, tc4, tc5);
//tr1.Append(shading);
return tr1;
}
public static TableRow rowcolumns(List<string> items)
{
// Create 1 row to the table.
TableRow tr1 = new TableRow();
for (var i = 0; i < items.Count; i++)
{
//Console.WriteLine("Amount is {0} and type is {1}", myMoney[i].amount, myMoney[i].type);
//TableCell tc1 = new TableCell(new Paragraph(new Run(new Text(items[i]))));
tr1.Append(cellcreaction(items[i]));
}
// Add a cell to each column in the row.
//TableCell tc1 = new TableCell(new Paragraph(new Run(new Text("Step"))));
//TableCell tc2 = new TableCell(new Paragraph(new Run(new Text("SubStep"))));
//TableCell tc3 = new TableCell(new Paragraph(new Run(new Text("Group"))));
//TableCell tc4 = new TableCell(new Paragraph(new Run(new Text("Description"))));
//TableCell tc5 = new TableCell(new Paragraph(new Run(new Text("ScreenShot"))));
//tr1.Append(tc1, tc2, tc3, tc4, tc5);
return tr1;
}
public static TableCell cellcreaction(string txt)
{
return new TableCell(new Paragraph(new Run(new Text(txt))));
}
public static Paragraph paragraph(string txt)
{
Paragraph para = new Paragraph();
Run run = para.AppendChild(new Run());
run.AppendChild(new Text(txt));
return para;
}
public static void InsertAPicture(string document, string fileName)
{
using (WordprocessingDocument wordprocessingDocument =
WordprocessingDocument.Open(document, true))
{
MainDocumentPart mainPart = wordprocessingDocument.MainDocumentPart;
ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Jpeg);
using (FileStream stream = new FileStream(fileName, FileMode.Open))
{
imagePart.FeedData(stream);
}
AddImageToBody(wordprocessingDocument, mainPart.GetIdOfPart(imagePart));
}
}
private static void AddImageToBody(WordprocessingDocument wordDoc, string relationshipId)
{
// Define the reference of the image.
var element =
new Drawing(
new DW.Inline(
new DW.Extent() { Cx = 990000L, Cy = 792000L },
new DW.EffectExtent()
{
LeftEdge = 0L,
TopEdge = 0L,
RightEdge = 0L,
BottomEdge = 0L
},
new DW.DocProperties()
{
Id = (UInt32Value)1U,
Name = "Picture 1"
},
new DW.NonVisualGraphicFrameDrawingProperties(
new A.GraphicFrameLocks() { NoChangeAspect = true }),
new A.Graphic(
new A.GraphicData(
new PIC.Picture(
new PIC.NonVisualPictureProperties(
new PIC.NonVisualDrawingProperties()
{
Id = (UInt32Value)0U,
Name = "New Bitmap Image.jpg"
},
new PIC.NonVisualPictureDrawingProperties()),
new PIC.BlipFill(
new A.Blip(
new A.BlipExtensionList(
new A.BlipExtension()
{
Uri =
"{28A0092B-C50C-407E-A947-70E740481C1C}"
})
)
{
Embed = relationshipId,
CompressionState =
A.BlipCompressionValues.Print
},
new A.Stretch(
new A.FillRectangle())),
new PIC.ShapeProperties(
new A.Transform2D(
new A.Offset() { X = 0L, Y = 0L },
new A.Extents() { Cx = 990000L, Cy = 792000L }),
new A.PresetGeometry(
new A.AdjustValueList()
)
{ Preset = A.ShapeTypeValues.Rectangle }))
)
{ Uri = "https://schemas.openxmlformats.org/drawingml/2006/picture" })
)
{
DistanceFromTop = (UInt32Value)0U,
DistanceFromBottom = (UInt32Value)0U,
DistanceFromLeft = (UInt32Value)0U,
DistanceFromRight = (UInt32Value)0U,
//EditId = "50D07946"
});
// Append the reference to body, the element should be in a Run.
wordDoc.MainDocumentPart.Document.Body.AppendChild(new Paragraph(new Run(element)));
}
}
}

How to use "content disposition attachment" in OpenXml

I have an ASP.NET MVC 4 site that creates an Excel file using OPEN XML SDK. My controller method generates the OPEN XML Excel document and is downloading it.
But the user should see the Excel file in the browser.
I know
Response.AddHeader("content-disposition", "attachment; filename=" + fileName + "");
is responsible for it. But I don't know how to implement this in openXnl method. I am not using http response here. Or how can I use it? Please help me on this
This is my Excel generating method, and I tried to implement AddHeader "content-disposition" but nothing works:
public static void GenerateExcelOpenXML(string FolderPath, DataSet tableSet)
{
WorkbookPart wBookPart = null;
var datetime = DateTime.Now.ToString().Replace("/", "_").Replace(":", "_");
string FilePath = FolderPath + "Report_" + datetime + ".xlsx";
using (SpreadsheetDocument spreadsheetDoc = SpreadsheetDocument.Create(FilePath, SpreadsheetDocumentType.Workbook))
{
wBookPart = spreadsheetDoc.AddWorkbookPart();
wBookPart.Workbook = new Workbook();
uint sheetId = 1;
spreadsheetDoc.WorkbookPart.Workbook.Sheets = new Sheets();
Sheets sheets = spreadsheetDoc.WorkbookPart.Workbook.GetFirstChild<Sheets>();
WorkbookStylesPart wbsp = wBookPart.AddNewPart<WorkbookStylesPart>();
wbsp.Stylesheet = CreateStylesheet();
wbsp.Stylesheet.Save();
foreach (DataTable table in tableSet.Tables)
{
WorksheetPart wSheetPart = wBookPart.AddNewPart<WorksheetPart>();
Sheet sheet = new Sheet() { Id = spreadsheetDoc.WorkbookPart.GetIdOfPart(wSheetPart),
SheetId = sheetId, Name = table.TableName };
sheets.Append(sheet);
SheetData sheetData = new SheetData();
wSheetPart.Worksheet = new Worksheet();
Row headerRow = new Row();
Columns columns = new Columns();
int ColumnNumber = 1;
foreach (DataColumn column in table.Columns)
{
Cell cell = new Cell();
cell.DataType = CellValues.String;
cell.CellValue = new CellValue(column.ColumnName);
cell.StyleIndex = 2;
headerRow.AppendChild(cell);
Column column1 = new Column();
column1.Width = 30;
column1.Min = Convert.ToUInt32(ColumnNumber);
column1.Max = Convert.ToUInt32(ColumnNumber);
column1.CustomWidth = true;
columns.AppendChild(column1);
ColumnNumber = ColumnNumber + 1;
}
wSheetPart.Worksheet.AppendChild(columns);
sheetData.AppendChild(headerRow);
foreach (DataRow dr in table.Rows)
{
Row row = new Row();
foreach (DataColumn column in table.Columns)
{
Cell cell = new Cell();
cell.DataType = CellValues.String;
cell.CellValue = new CellValue(dr[column].ToString());
cell.StyleIndex = 1;
row.AppendChild(cell);
}
sheetData.AppendChild(row);
}
sheetId++;
wSheetPart.Worksheet.AppendChild(sheetData);
// sheetData.AddHeader("content-disposition", "attachment; filename=" + fileName + "");
// how can I implement here?
}
}
}

I'm having problems zooming into images that are in rows of an UITableView in Xamarin.iOS

I have a tableView inside a tabView, and my rows in the tableView contain images. I would like to zoom into the said images (I put them inside a scrollView and set the max/min zoom and I set ViewForZoomingInScrollView), but it seems I can't get the zoom to trigger because they are small images 50x56 or some other gesture/event is interfeiring. I use the same zoom code on another part of my app and it works perfectly. Has anyone come across the same or similar problem or knows a possible solution?
EDIT:
protected DocumentBaseCell()
: base(UITableViewCellStyle.Default, new NSString("TableCell"))
{
...
documentImage = new UIImageView();
documentImage.Image = UIImage.FromBundle("LaunchImage");
documentImage.ContentMode = UIViewContentMode.ScaleAspectFit;
documentImage.Layer.ZPosition = 0;
imageScrollView = new UIScrollView();
imageScrollView.ClipsToBounds = false;
imageScrollView.ContentSize = new CGSize(50, 56);
imageScrollView.MaximumZoomScale = 8f;
imageScrollView.MinimumZoomScale = 1f;
imageScrollView.Add(documentImage);
imageScrollView.ViewForZoomingInScrollView += (UIScrollView sv) =>
{
imageScrollView.ContentSize = new CGSize(documentImage.Frame.Width, documentImage.Frame.Height);
return documentImage;
};
imageScrollView.DidZoom += (object sender, EventArgs e) =>
{
//(sender as UIView).Layer.ZPosition = 2000;
};
imageScrollView.ZoomingEnded += (object sender, ZoomingEndedEventArgs e) =>
{
(sender as UIScrollView).SetZoomScale(0f, true);
(sender as UIView).Layer.ZPosition = 0;
this.Layer.ZPosition = 0;
};
ContentView.Add(imageScrollView);
...
}
And this is the UpdateCell method:
internal virtual void UpdateCell(DocumentModel doc, string sup, string
docType, string user, string date, UIImage image)
{
if (image != null)
{
this.documentImage.Image = image;
}
...
}
The Frame is set aswell:
public override void LayoutSubviews()
{
base.LayoutSubviews();
imageScrollView.Frame = new CGRect(0, 2, 50, 56);
documentImage.Frame = new CGRect(0, 0, 50, 56);
}
I think you should give a frame to imageScrollView and documentImage, I download the official tableView sample project and add your code there, it zooms well.
public override void LayoutSubviews ()
{
base.LayoutSubviews ();
imageScrollView.Frame = new CGRect(ContentView.Bounds.Width - 233, 5, 133, 133);
headingLabel.Frame = new CGRect(5, 4, ContentView.Bounds.Width - 63, 25);
subheadingLabel.Frame = new CGRect(100, 18, 100, 20);
imageView.Frame = imageScrollView.Bounds;
}
I uploaded a sample project here and you can check it.

UITableView with SearchView makes new cells overlap old ones on search

Iam implementing a SearchView to filter the data in my UITableView. Iam able to search successfully, the only issue is when the UITableView data gets filtered, the old cells still exist and the filtered ones overlap them giving me a messy output. I have cleared the Table source as suggested by my answers on SO, but still not resolved the problem.
Here is what Iam trying to do:
FilterController
void searchFiler_TextChanged(object sender, UISearchBarTextChangedEventArgs e)
{
if (!string.IsNullOrEmpty(e.SearchText))
{
ppTable.Source = null;
AppDelegate.filteredList = null;
ppTable.ReloadData();
filteredModelList = filter(dupes, e.SearchText);
mAdapter = new PeoplePlacesSource(filteredModelList, "");
ppTable.Source = mAdapter;
ppTable.ReloadData();
}
else
{
ppTable.Source = null;
mAdapter = new PeoplePlacesSource(dupes, "");
searchFiler.TextChanged += searchFiler_TextChanged;
mAdapter.TableRowSelected += mAdapter_TableRowSelected;
ppTable.Source = mAdapter;
ppTable.ReloadData();
}
}
PeoplePlacesSource
public override UITableViewCell GetCell(UITableView tableView, Foundation.NSIndexPath indexPath)
{
cell = tableView.DequeueReusableCell("PeoplePlacesCell_Cell") as PeoplePlacesCell ?? PeoplePlacesCell.Create();
subList = userList.ElementAt(indexPath.Row);
cell.UpdatePeoplePlacesCell(subList);
return cell;
}
PeoplePlacesCell
internal void UpdatePeoplePlacesCell(System.Linq.IGrouping<string, Models.EmployeeModel> subList)
{
var yPosition =15;
var xPosition = 10;
var imgDefault = new UIImageView();
imgDefault.Frame = new CoreGraphics.CGRect(10, viewParent.Frame.Y, 60,60);
imgDefault.Image = UIImage.FromFile("ic_appicon.png");
CALayer profileImageCircle = imgDefault.Layer;
profileImageCircle.CornerRadius = 28;
profileImageCircle.BorderWidth = 2;
profileImageCircle.BorderColor = new CoreGraphics.CGColor(211, 34, 41);
profileImageCircle.MasksToBounds = true;
imgDefault.ClipsToBounds = true;
viewParent.AddSubview(imgDefault);
var labelUserName = new UILabel();
labelUserName.Frame = new CoreGraphics.CGRect(0, 0, viewContainer.Frame.Width, 30);
labelUserName.TextColor = UIColor.FromRGB(211, 34, 41);
labelUserName.Text = subList.Key ;
labelUserName.ClipsToBounds = true;
labelUserName.Font = UIFont.BoldSystemFontOfSize(17);
viewContainer.AddSubview(labelUserName);
var mList = subList.Take(5);
foreach (var employeeModel in mList)
{
var labelPlace = new UILabel();
labelPlace.Frame = new CoreGraphics.CGRect(0, yPosition, viewContainer.Frame.Width, 50);
if (employeeModel.Place.Contains(","))
{
labelPlace.Text = employeeModel.Place.Substring(0, employeeModel.Place.IndexOf(","));
}
else
{
labelPlace.Text = employeeModel.Place;
}
labelPlace.Font = UIFont.FromName(labelPlace.Font.Name, 12f);
labelUserName.SizeToFit();
labelPlace.ClipsToBounds = true;
viewContainer.AddSubview(labelPlace);
yPosition += 15;
}
}
How can I solve this? Any help is appreciated
Do you have the same problem after scroll? You cells are reused, but I don't see code for removing added subviews. Try to remove all subviews you added, before reusing cells.

Multiple Bills Printing in C#

I am developing a module in a billing system for a national Utility. The module is supposed to pick all successfully billed customers and print their bills.Bills are written as text files and saved on a local folder and the program has to pick them up and print them one by one.I'm using a DFX-9000 printer and pre-formatted roll paper,however,each time a new bill comes in,the printer skips some space before it prints it which distorts the 2nd and following bills.
I tried putting all the bills in a single text file which prints well when opened in notepad but not in my code.
Here is part of my code
Font printFont = new Font("Lucida Console", 10);
//static string filename;
StreamReader reader = new StreamReader(Filename);
public void Print()
{
try
{
PrintDocument pd = new PrintDocument();
pd.DefaultPageSettings.PaperSize = new System.Drawing.Printing.PaperSize("myPaper", 826, 1169);
pd.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);
//pd.DefaultPageSettings.PrinterSettings.IsPlotter = true;
pd.DefaultPageSettings.PrinterResolution.Kind = PrinterResolutionKind.Custom;
pd.PrintPage += new PrintPageEventHandler(this.PrintTextFileHandler);
pd.Print();
if (reader != null)
reader.Close();
Console.WriteLine("Printout Complete");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private void PrintTextFileHandler(object sender, PrintPageEventArgs pe)
{
StringFormat sf = new StringFormat();
Graphics g = pe.Graphics;
float linesPerPage = 0;
float yPos = 0;
int count = 0;
float leftMargin = 40;//pe.MarginBounds.Left;
float topMargin = pe.MarginBounds.Top;
string line = null;
linesPerPage = 500;// pe.MarginBounds.Height / printFont.GetHeight(g);
while (count <= linesPerPage &&((line = reader.ReadLine()) != null))
{
yPos = topMargin + (count * printFont.GetHeight(g));
g.DrawString(line, printFont, Brushes.Black, leftMargin, yPos);
count++;
}
if (line != null)
{
pe.HasMorePages = true;
}
else
{
pe.HasMorePages = false;
}
Could your printing.papersize be wrong? I notice it's 1169, doesn't standard paper stop at 1100?

Resources