Excel range Style: specifying Borders via VSTO doesn't work - excel

Instead of formatting ranges by setting individual formatting properties one by one, I am trying to use Excel Styles, because it seems to be faster at formatting large numbers of cells. I define a Style once, and then apply it to Ranges like this:
var cell = worksheet.Cells[row, column];
cell.Style = "MyCustomStyle";
It works perfectly for Interior Color and Font, but I am running into weird issues when trying to work with Borders. When I try to define what borders to show on a range, and how they should be formatted, I get unpredictable results, and can't find a way to control it.
The following method creates a Style named ListRowStyle;
private static void CreateListRowStyle(Workbook workbook)
{
var listRowStyle = workbook.Styles.Add(ListRowStyle);
listRowStyle.Interior.Color = ColorTranslator.ToOle(Color.LightGray);
listRowStyle.Font.Color = ColorTranslator.ToOle(Color.DarkBlue);
listRowStyle.Font.Bold = true;
listRowStyle.IncludeBorder = true;
listRowStyle.Borders.Color = ColorTranslator.ToOle(Color.Black);
listRowStyle.Borders.LineStyle = XlLineStyle.xlContinuous;
listRowStyle.Borders.Weight = XlBorderWeight.xlMedium;
}
This creates every single border in the range (vertical, horizontal and diagonal) - so far, so good. However, when I try to display only, say, the top and bottom borders, using the following code, problems start happening:
private static void CreateEditableListRowStyle(Workbook workbook)
{
var editableListRowStyle = workbook.Styles.Add(EditableListRowStyle);
editableListRowStyle.Interior.Color = ColorTranslator.ToOle(Color.Yellow);
editableListRowStyle.Font.Color = ColorTranslator.ToOle(Color.Red);
editableListRowStyle.Font.Bold = false;
editableListRowStyle.IncludeBorder = true;
editableListRowStyle.Borders[XlBordersIndex.xlEdgeLeft].LineStyle = XlLineStyle.xlLineStyleNone;
editableListRowStyle.Borders[XlBordersIndex.xlEdgeRight].LineStyle = XlLineStyle.xlLineStyleNone;
editableListRowStyle.Borders[XlBordersIndex.xlDiagonalDown].LineStyle = XlLineStyle.xlLineStyleNone;
editableListRowStyle.Borders[XlBordersIndex.xlDiagonalUp].LineStyle = XlLineStyle.xlLineStyleNone;
editableListRowStyle.Borders[XlBordersIndex.xlEdgeTop].LineStyle = XlLineStyle.xlContinuous;
editableListRowStyle.Borders[XlBordersIndex.xlEdgeTop].Weight = XlBorderWeight.xlMedium;
editableListRowStyle.Borders[XlBordersIndex.xlEdgeBottom].LineStyle = XlLineStyle.xlContinuous;
editableListRowStyle.Borders[XlBordersIndex.xlEdgeBottom].Weight = XlBorderWeight.xlThin;
}
The color styling happens, but no borders show up. Things get even weirder when I modify the code to format the Left and Right border like this:
private static void CreateEditableListRowStyle(Workbook workbook)
{
var editableListRowStyle = workbook.Styles.Add(EditableListRowStyle);
editableListRowStyle.Interior.Color = ColorTranslator.ToOle(Color.Yellow);
editableListRowStyle.Font.Color = ColorTranslator.ToOle(Color.Red);
editableListRowStyle.Font.Bold = false;
editableListRowStyle.IncludeBorder = true;
editableListRowStyle.Borders[XlBordersIndex.xlEdgeLeft].LineStyle = XlLineStyle.xlContinuous;
editableListRowStyle.Borders[XlBordersIndex.xlEdgeLeft].Weight = XlBorderWeight.xlMedium;
editableListRowStyle.Borders[XlBordersIndex.xlEdgeRight].LineStyle = XlLineStyle.xlContinuous;
editableListRowStyle.Borders[XlBordersIndex.xlEdgeRight].Weight = XlBorderWeight.xlMedium;
editableListRowStyle.Borders[XlBordersIndex.xlDiagonalDown].LineStyle = XlLineStyle.xlLineStyleNone;
editableListRowStyle.Borders[XlBordersIndex.xlDiagonalUp].LineStyle = XlLineStyle.xlLineStyleNone;
editableListRowStyle.Borders[XlBordersIndex.xlEdgeTop].LineStyle = XlLineStyle.xlContinuous;
editableListRowStyle.Borders[XlBordersIndex.xlEdgeTop].Weight = XlBorderWeight.xlMedium;
editableListRowStyle.Borders[XlBordersIndex.xlEdgeBottom].LineStyle = XlLineStyle.xlContinuous;
editableListRowStyle.Borders[XlBordersIndex.xlEdgeBottom].Weight = XlBorderWeight.xlThin;
}
At that point, the top and bottom borders still don't show up; on the other hand, I get a Left border that shows up, but no Right border. Uh?
So - am I doing something wrong, or is setting Borders on a Style via VSTO just not working? Note that the following code, which is a very close translation of the VSTO/C# code in VBA, works exactly as I would expect it to.
Sub Styling()
ActiveWorkbook.Styles.Add Name:="VbaStyle"
With ActiveWorkbook.Styles("VbaStyle")
.IncludeBorder = True
End With
ActiveWorkbook.Styles("VbaStyle").Borders(xlLeft).LineStyle = xlNone
ActiveWorkbook.Styles("VbaStyle").Borders(xlRight).LineStyle = xlNone
ActiveWorkbook.Styles("VbaStyle").Borders(xlDiagonalDown).LineStyle = xlNone
ActiveWorkbook.Styles("VbaStyle").Borders(xlDiagonalUp).LineStyle = xlNone
With ActiveWorkbook.Styles("VbaStyle").Borders(xlTop)
.LineStyle = xlContinuous
.Weight = xlMedium
End With
With ActiveWorkbook.Styles("VbaStyle").Borders(xlBottom)
.LineStyle = xlContinuous
.Weight = xlThin
End With
End Sub
This is on Windows 7, Excel 2007.

Try using xlLeft, xlRight, xlTop, xlBottom instead of xlEdgeLeft, xlEdgeRight, xlEdgeTop, xlEdgeBottom

I was trying for sometime and came across your question and got some heads-up.
Thanks for that.
Was able to create the style using the optional parameter of basedOn like below:
var activeSheet = workbook.ActiveSheet as Worksheet;
Range first = activeSheet.Range["A1"];
first.Borders.Item[XlBordersIndex.xlEdgeBottom].Color = Color.FromArgb(0, 16, 80);
first.Borders.Item[XlBordersIndex.xlEdgeBottom].Weight = XlBorderWeight.xlThick;
first.Borders.Item[XlBordersIndex.xlEdgeBottom].LineStyle = XlLineStyle.xlContinuous;
Style myStyle = o9Workbook.Styles.Add("MyStyle",first);
//reset the first to normal style
first.Style = "Normal";
Hope it helps someone!

Related

Receive error when double click data in Listbox

I am newbies in VBA. Recently I have created a "Search Form". The search data have 21 columns which will display in the "Search List Box". Unfortunately, it only can show until 9 columns and will return an error for the 10 and above data. Your guidance is very much appreciated. Below is my code:
Private Sub dtlist_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
CDSv1.dptname.Text = CDSv1.dtlist.Column(1)
CDSv1.dptadd.Text = CDSv1.dtlist.Column(2)
CDSv1.divcom.Text = CDSv1.dtlist.Column(3)
CDSv1.ctcname.Text = CDSv1.dtlist.Column(4)
CDSv1.ctcno.Text = CDSv1.dtlist.Column(5)
CDSv1.nid.Text = CDSv1.dtlist.Column(6)
CDSv1.serno.Text = CDSv1.dtlist.Column(7)
CDSv1.ipinfo.Text = CDSv1.dtlist.Column(8)
CDSv1.snet.Text = CDSv1.dtlist.Column(9)
CDSv1.gateway.Text = CDSv1.dtlist.Column(10) '<---- The error starts here.
CDSv1.vlinfo.Text = CDSv1.dtlist.Column(11)
CDSv1.netcatcom.Text = CDSv1.dtlist.Column(12)
CDSv1.netsubcatcom.Text = CDSv1.dtlist.Column(13)
CDSv1.ispcom.Text = CDSv1.dtlist.Column(14)
CDSv1.snscom.Text = CDSv1.dtlist.Column(15)
CDSv1.cirt.Text = CDSv1.dtlist.Column(16)
CDSv1.bdwh.Text = CDSv1.dtlist.Column(17)
CDSv1.statcom.Text = CDSv1.dtlist.Column(18)
CDSv1.remf.Text = CDSv1.dtlist.Column(20)
End Sub

NPOI set Explicit Column Type Not working properly

I'm using NPOI Excel Library to generate a Excel file, in that Excel file i'm explicitly define column type for Columns like Date,String etc.
Im using the following code to achive this.
var row = sheet.CreateRow(currentNPOIRowIndex++);
for (var colIndex = 0; colIndex < exportData.Columns.Count; colIndex++)
{
ICell cell = null;
cell = row.CreateCell(colIndex);
if (exportData.Columns[colIndex].DataType == typeof(DateTime))
{
if (exportData.Rows[rowIndex][colIndex].ToString() != "")
{
cell.SetCellValue((DateTime)exportData.Rows[rowIndex][colIndex]);
cell.CellStyle = (NPOI.HSSF.UserModel.HSSFCellStyle)book.CreateCellStyle();
cell.CellStyle.DataFormat = book.CreateDataFormat().GetFormat("yyyyMMdd HH:mm:ss");
cell = null;
}
else
cell.SetCellValue(exportData.Rows[rowIndex][colIndex].ToString());
}
else
cell.SetCellValue(exportData.Rows[rowIndex][colIndex].ToString());
}
}
The above code works fine for 42 rows i.e. it correctly set the Column Type,but after 42 rows Column Type doesn't apply.
Any help will be highly appreciated.
you'll required to set default column style if you want to set column format for all cells of that column. Please see the below example from xssf format. Syntax may differ for your hssf format but it will give you idea what you are missing.
I am providing you from my working code. I am using NPOI version 2.2.1.0.
can you comment line //cell = null;
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = (XSSFSheet)workbook.CreateSheet("Template");
XSSFFont defaultFont = (XSSFFont)workbook.CreateFont();
defaultFont.FontHeightInPoints = (short)10;
XSSFCellStyle headerStyle = (XSSFCellStyle)workbook.CreateCellStyle();
headerStyle.WrapText = true;
XSSFCellStyle defaultStyle = (XSSFCellStyle)workbook.CreateCellStyle();
XSSFDataFormat defaultDataFormat = (XSSFDataFormat)workbook.CreateDataFormat();
defaultStyle.SetDataFormat(defaultDataFormat.GetFormat("000-000-0000"));
defaultStyle.FillBackgroundColor = IndexedColors.LightYellow.Index;
defaultStyle.FillForegroundColor = IndexedColors.LightTurquoise.Index;
defaultStyle.SetFont(defaultFont);
var row = sheet.CreateRow(0);
for (int headerCount = 0; headerCount < headers.Count(); headerCount++)
{
row.CreateCell(headerCount).SetCellValue(headers[headerCount]);
row.Cells[headerCount].CellStyle = headerStyle;
sheet.SetDefaultColumnStyle(headerCount, defaultStyle);
}

How can I shift the "subitems" in an Excel PivotTable to another column?

I generate an Excel sheet which contains data formatted like so:
IOW, the "Total Packages", "Total Purchases", "Average Price", and "% of Total" values are located in a column of their own (Data) for each overarching (or sidearching) description.
When I PivotTablize this data, it places these values beneath each description:
This makes sense, but those accustomed to the previous appearance want it to be replicated in the PivotTable. How can I shift the Description "subitems" in the PivotTable to their own column?
This is the code I use to generate the PivotTable:
private void PopulatePivotTableSheet()
{
string NORTHWEST_CORNER_OF_PIVOT_TABLE = "A6";
AddPrePivotTableDataToPivotTableSheet();
var dataRange = rawDataWorksheet.Cells[rawDataWorksheet.Dimension.Address];
dataRange.AutoFitColumns();
var pivotTable = pivotTableWorksheet.PivotTables.Add(
pivotTableWorksheet.Cells[NORTHWEST_CORNER_OF_PIVOT_TABLE],
dataRange,
"PivotTable");
pivotTable.MultipleFieldFilters = true;
pivotTable.GridDropZones = false;
pivotTable.Outline = false;
pivotTable.OutlineData = false;
pivotTable.ShowError = true;
pivotTable.ErrorCaption = "[error]";
pivotTable.ShowHeaders = true;
pivotTable.UseAutoFormatting = true;
pivotTable.ApplyWidthHeightFormats = true;
pivotTable.ShowDrill = true;
// Row field[s]
var descRowField = pivotTable.Fields["Description"];
pivotTable.RowFields.Add(descRowField);
// Column field[s]
var monthYrColField = pivotTable.Fields["MonthYr"];
pivotTable.ColumnFields.Add(monthYrColField);
// Data field[s]
var totQtyField = pivotTable.Fields["TotalQty"];
pivotTable.DataFields.Add(totQtyField);
var totPriceField = pivotTable.Fields["TotalPrice"];
pivotTable.DataFields.Add(totPriceField);
// Don't know how to calc these vals here, so have to grab them from the source data sheet
var avgPriceField = pivotTable.Fields["AvgPrice"];
pivotTable.DataFields.Add(avgPriceField);
var prcntgOfTotalField = pivotTable.Fields["PrcntgOfTotal"];
pivotTable.DataFields.Add(prcntgOfTotalField);
}
So there is one RowField ("MonthYr") with values such as "201509" and "201510", one ColumnField ("Description") and four DataFields, which align themseles under the Description column field. I want to shift those four fields to the right, to their own column, and the Description label to be vertically centered between those four values to their left. [How] is this possible?
Try changing the layout of your table with
pivotTable.RowAxisLayout xlTabularRow
pivotTable.MergeLabels = True
this is the result:
A little script in C# with Interop.Excel. Included the using ;)
using Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel;
var excelApp = new Excel.Application();
Excel.Workbook wb = excelApp.Workbooks.Open(#"e:\42\TestSO.xlsx");
Worksheet ws = wb.Worksheets["SheetName"];
PivotTable pt = ws.PivotTables("DynamicTableName");
pt.RowAxisLayout(XlLayoutRowType.xlTabularRow);
pt.MergeLabels = true;
wb.Save();
wb.Close();
Marshal.ReleaseComObject(ws);
It's all about PivotTable layout / design... here's the manual way - Salvador has the VBA way :)...

Aspose Slides Table Cell Insert HTML content

I am working with Aspose slides to generate PPT in my application, I ran into a situation where I need to insert HTML text into Table Cell, I verified all blogs no one given answer to me. If any body know here please let me know. Thanks In advance.
You can use the TextFrame's paragraph associated with each cell to insert HTML using Aspose.Slides for .NET. Check the following code:
//Instantiate Presentation class that represents PPTX file
using (Presentation pres = new Presentation())
{
//Access first slide
ISlide sld = pres.Slides[0];
//Define columns with widths and rows with heights
double[] dblCols = { 250, 250};
double[] dblRows = { 150, 130, 130 };
//Add table shape to slide
ITable tbl = sld.Shapes.AddTable(100, 50, dblCols, dblRows);
//Set border format for each cell
foreach (IRow row in tbl.Rows)
foreach (ICell cell in row)
{
cell.BorderTop.FillFormat.FillType = FillType.Solid;
cell.BorderTop.FillFormat.SolidFillColor.Color = Color.Red;
cell.BorderTop.Width = 5;
cell.BorderBottom.FillFormat.FillType = FillType.Solid;
cell.BorderBottom.FillFormat.SolidFillColor.Color = Color.Red;
cell.BorderBottom.Width = 5;
cell.BorderLeft.FillFormat.FillType = FillType.Solid;
cell.BorderLeft.FillFormat.SolidFillColor.Color = Color.Red;
cell.BorderLeft.Width = 5;
cell.BorderRight.FillFormat.FillType = FillType.Solid;
cell.BorderRight.FillFormat.SolidFillColor.Color = Color.Red;
cell.BorderRight.Width = 5;
}
//Adding html text in text frame
tbl[0, 0].TextFrame.Paragraphs.AddFromHtml(#"<html><body><p><b>This text is bold</b></p>
<p><i>This text is italic</i></p><p>This is<sub> subscript</sub> and <sup>superscript</sup></p>
</body></html>");
//Write PPTX to Disk
pres.Save("d:\\data\\table_html.pptx", Aspose.Slides.Export.SaveFormat.Pptx);
}
P.S. I am working as social media developer at Aspose.

setting cell style not working

i'm working with apache poi and XLSX file. i use xssf classes to dynamically create a spreadsheet.
i'd like to set cell's style in a for loop, but it doesn't seem to work...here's my code :
for(int i=1;i<=gc.getActualMaximum(GregorianCalendar.DAY_OF_MONTH);i++,gc.add(GregorianCalendar.DATE, 1),righe++){
Row r = foglio.createRow(righe);
if(getDayOfWeek(gc)== 6 || getDayOfWeek(gc) == 7){
XSSFCellStyle cs1 = wb.createCellStyle();
cs1.setFillBackgroundColor(IndexedColors.YELLOW.getIndex());
cs1.setFillPattern(CellStyle.SOLID_FOREGROUND);
XSSFFont f = wb.createFont();
f.setBold(true);
f.setColor(IndexedColors.RED.getIndex());
cs1.setFont(f);
Cell c1 = r.createCell(0);
c1.setCellValue(cost.getGiorni().get(getDayOfWeek(gc)-1).getNomeGiorno());
c1.setCellStyle(cs1);
Cell c2 = r.createCell(1);
c2.setCellValue(i);
c2.setCellStyle(cs1);
}
r.createCell(0).setCellValue(cost.getGiorni().get(getDayOfWeek(gc)-1).getNomeGiorno());
r.createCell(1).setCellValue(i);
...this i just a portion of the code...
i can't understand why is not working. Seems like the cellstyle is ignored or overwrited....
any clue ?
CellStyles are per-workbook, and there's a hard limit that Excel imposes on the numbers that a file is allowed to have, so you need to make sure you create the cell style once outside the loop.
Your code would then look something like:
XSSFCellStyle cs1 = wb.createCellStyle();
cs1.setFillBackgroundColor(IndexedColors.YELLOW.getIndex());
cs1.setFillPattern(CellStyle.SOLID_FOREGROUND);
XSSFFont f = wb.createFont();
f.setBold(true);
f.setColor(IndexedColors.RED.getIndex());
cs1.setFont(f);
for(int i=1;i<=gc.getActualMaximum(GregorianCalendar.DAY_OF_MONTH) i++,gc.add(GregorianCalendar.DATE, 1),righe++){
Row r = foglio.createRow(righe);
if(getDayOfWeek(gc)== 6 || getDayOfWeek(gc) == 7){
Cell c1 = r.createCell(0);
c1.setCellValue(cost.getGiorni().get(getDayOfWeek(gc)-1).getNomeGiorno());
c1.setCellStyle(cs1);
Cell c2 = r.createCell(1);
c2.setCellValue(i);
c2.setCellStyle(cs1);
}
}
If you're having issues with the styling not looking quite as you expect, the best option is to style a cell as you want it in Excel, save the file, read that into POI, and review the cell style that Excel wrote. Sometimes, Excel can do some strange things that take some getting used to, so check what it does to work out what you need to be doing!
You can use Following method, perhaps this will resolve your problem.
public static void setCellColorAndFontColor(XSSFCell cell, IndexedColors FGcolor, IndexedColors FontColor ){
XSSFWorkbook wb = cell.getRow().getSheet().getWorkbook();
CellStyle style = wb.createCellStyle();
XSSFFont font = wb.createFont();
font.setBold(true);
font.setColor(FontColor.getIndex());
style.setFont(font);
style.setFillForegroundColor(FGcolor.getIndex());
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
cell.setCellStyle(style);
}
When you are calling this method the way should be like
setCellColorAndFontColor(cell, IndexedColors.BLACK, IndexedColors.WHITE);
will create bold & white font text color with black cell background color in the sheet.
I think the
.setFillPattern(CellStyle.SOLID_FOREGROUND);
got changed to
.setFillPattern(FillPatternType.SOLID_FOREGROUND);
this works for me:
//design settings for header row
Font headerFont = wb.createFont();
headerFont.setColor(IndexedColors.WHITE.getIndex());
CellStyle headerCellStyle = wb.createCellStyle();
headerCellStyle.setFont(headerFont);
headerCellStyle.setAlignment(HorizontalAlignment.CENTER);
headerCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
headerCellStyle.setFillForegroundColor(IndexedColors.BLACK.getIndex());
headerCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);

Resources