NPOI apply font to entire row of cells - c#

I'm using NPOI to export my data to excel. The problem is I found it really hard for any kind of graphical changes.
This is the method I'm using now to apply bold font to my cells.
//Create new Excel workbook
var workbook = new HSSFWorkbook();
//Create new Excel sheet
var sheet = workbook.CreateSheet();
//Create a header row
var headerRow = sheet.CreateRow(0);
var boldFont = workbook.CreateFont();
boldFont.FontHeightInPoints = 11;
boldFont.FontName = "Calibri";
boldFont.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.Bold;
int cellCounter = 0;
//day
var cell = headerRow.CreateCell(cellCounter++);
cell.SetCellValue("Day");
cell.CellStyle = workbook.CreateCellStyle();
cell.CellStyle.SetFont(boldFont);
//month
cell = headerRow.CreateCell(cellCounter++);
cell.SetCellValue("Month");
cell.CellStyle = workbook.CreateCellStyle();
cell.CellStyle.SetFont(boldFont);
//year
cell = headerRow.CreateCell(cellCounter++);
cell.SetCellValue("Year");
cell.CellStyle = workbook.CreateCellStyle();
cell.CellStyle.SetFont(boldFont);
//machine name
cell = headerRow.CreateCell(cellCounter++);
cell.SetCellValue("Machine unique name");
cell.CellStyle = workbook.CreateCellStyle();
cell.CellStyle.SetFont(boldFont); //and so on
Is there a ,,cleaner" way to do this ? Now i have to manually add font for individual cells. I've tried many ways to do this on the internet and nothing seems to be working. Do you have a tested way to apply style to specific column or row ?
OffTopic: If not can you provide me with some good open source libraries with decent documentation and support that allow excel export (learning new dll is a pain but... :) what can you do)?

I'm doing something similar and modified my take on it closer for your use:
private string[] columnHeaders =
{
"Day",
"Month",
"Year",
"Machine Unique Name"
}
private void buildSheet(HSSFWorkbook wb, DataTable data, string sheetName)
{
var cHelp = wb.GetCreationHelper();
var sheet = wb.CreateSheet(sheetName);
HSSFFont hFont = (HSSFFont)wb.CreateFont();
hFont.FontHeightInPoints = 11;
hFont.FontName = "Calibri";
hFont.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.Bold;
HSSFCellStyle hStyle = (HSSFCellStyle)wb.CreateCellStyle();
hStyle.SetFont(hFont);
IRow headerRow = sheet.CreateRow(1);
int cellCount = 1;
foreach (string str in columnHeaders)
{
HSSFCell cell = (HSSFCell)headerRow.CreateCell(cellCount);
cell.SetCellValue(cHelp.CreateRichTextString((str)));
cell.CellStyle = hStyle;
cellCount += 1;
}
This iterates over however many headers you want starting at the second cell (cellCount = 1) second row (sheet.CreateRow(1)).

Related

How to import specific excel range to datagridview

I want to import an excel file to datagridview using GemBox. Im fairly new to GemBox and I can't seem to figure out how. I only want to import from cell "A9" to cell "H32".
var workbook = ExcelFile.Load(openFileDialog.FileName);
DataGridViewConverter.ExportToDataGridView(workbook.Worksheets.ActiveWorksheet, this.dgvMain, new ExportToDataGridViewOptions() { ColumnHeaders = true });
Thanks!
Here is how you can import specific cells:
var workbook = ExcelFile.Load(openFileDialog.FileName);
var worksheet = workbook.Worksheets.ActiveWorksheet;
var options = new ExportToDataGridViewOptions();
options.ColumnHeaders = true;
options.StartRow = 8; // Start from row 9, index 8.
options.NumberOfRows = 24; // End with row 32.
options.StartColumn = 0; // start with column A, index 0.
options.NumberOfColumns = 8; // End with column H.
DataGridViewConverter.ExportToDataGridView(worksheet, this.dgvMain, options);
Also here is another way how you can specify the same, by using the properties from CellRange object:
var workbook = ExcelFile.Load(openFileDialog.FileName);
var worksheet = workbook.Worksheets.ActiveWorksheet;
var range = worksheet.Cells.GetSubrange("A9:H32");
var options = new ExportToDataGridViewOptions();
options.ColumnHeaders = true;
options.StartRow = range.FirstRowIndex;
options.NumberOfRows = range.Height;
options.StartColumn = range.FirstColumnIndex;
options.NumberOfColumns = range.Width;
DataGridViewConverter.ExportToDataGridView(worksheet, this.dgvMain, options);

Setting the background color for specific cells in HSSFWork sheet using C#

I am trying to generate an excel sheet using HSSFWorkbook. I want to set the background color of a cell. I am using HSSFWorkbook, but am unfortunately unable to get the background color.
I need to set some cells to the same color and some other cells to more than one color.
My code is so far:
HSSFWorkbook workbook = new HSSFWorkbook();
MemoryStream memoryStream = new MemoryStream();
DataSet repds = exceldetils.ToDataSet("Batch");
HSSFSheet sheets = (NPOI.HSSF.UserModel.HSSFSheet)workbook.CreateSheet("Batch");
HSSFRow headerRow = (NPOI.HSSF.UserModel.HSSFRow)sheets.CreateRow(0);
//
List<string> columnnames = new List<string>();
foreach (DataColumn column in repds.Tables[0].Columns)
{
//column.ColumnName = HSSFFont.FONT_ARIAL;
// columnnames.Add(column.ColumnName);
headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
}
var cHelp = workbook.GetCreationHelper();
HSSFFont hFont = (HSSFFont)workbook.CreateFont();
hFont.Boldweight = (short)FontBoldWeight.Bold;
hFont.Color = HSSFColor.Black.Index;
hFont.FontHeightInPoints = 10 ;
HSSFCellStyle hs = workbook.CreateCellStyle();
HSSFCellStyle hStyle =(HSSFCellStyle) workbook.CreateCellStyle();
hStyle.SetFont(hFont);
hStyle.BorderBottom = BorderStyle.Medium;
hStyle.FillBackgroundColor = HSSFColor.Black.Index;
hStyle.FillPattern = FillPattern.SolidForeground;
int cellCount = 0;
foreach (string str in columnnames)
{
HSSFCell cell = (HSSFCell)headerRow.CreateCell(cellCount);
cell.SetCellValue(cHelp.CreateRichTextString((str)));
cell.CellStyle = hStyle;
cellCount += 1;
}
int rowIndex = 1;
foreach (DataRow row1 in repds.Tables[0].Rows)
{
HSSFRow dataRow = (NPOI.HSSF.UserModel.HSSFRow)sheets.CreateRow(rowIndex);
foreach (DataColumn column in repds.Tables[0].Columns)
{
dataRow.CreateCell(column.Ordinal).SetCellValue(row1[column].ToString());
}
rowIndex++;
}
workbook.Write(memoryStream);
//memoryStream.Flush();
//memoryStream.GetBuffer();

NPOI WrapText isn't working?

I am trying to create a column with WrapText set to true for an XLSX file using NPOI.
The following does not seem to work:
var workbook = new XSSFWorkbook();
var headerRow = sheet.CreateRow(0);
var cellType = CellType.String;
var colStyle = sheet.GetColumnStyle(3);
colStyle.WrapText = true;
sheet.SetDefaultColumnStyle(3, colStyle);
headerRow.CreateCell(0, cellType).SetCellValue("Name");
headerRow.CreateCell(3, cellType).SetCellValue("Comments");
var font = workbook.CreateFont();
font.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.Bold;
XSSFCellStyle style = (XSSFCellStyle)workbook.CreateCellStyle();
style.SetFont(font);
style.FillPattern = NPOI.SS.UserModel.FillPattern.SolidForeground;
style.FillForegroundColor = IndexedColors.Grey25Percent.Index;
style.IsLocked = false;
style.WrapText = true;
for (int i = 0; i < 6; i++)
{
var cell = headerRow.Cells[i];
cell.CellStyle = style;
}
headerRow.RowStyle = style;
sheet.SetColumnWidth(0, 30 * 256);
sheet.SetColumnWidth(1, 20 * 256);
sheet.SetColumnWidth(2, 20 * 256);
sheet.SetColumnWidth(3, 50 * 256);
sheet.SetColumnWidth(4, 30 * 256);
sheet.SetColumnWidth(5, 50 * 256);
int rowNumber = 1;
style = (XSSFCellStyle)workbook.CreateCellStyle();
style.IsLocked = false;
style.WrapText = true;
foreach (MemberListViewModel member in members)
{
var row = sheet.CreateRow(rowNumber++);
row.CreateCell(0).SetCellValue(member.FullName);
row.CreateCell(3).SetCellValue(member.endowed_professorship);
}
workbook.Write(output);
Naturally, the documentation is a little light for this one.
Any suggestions on changing the code? Otherwise, it seems to work fine.
I just can't get the wraptext to work.
EDIT:
After posting the question, I revised my code to use Reflection to detach the code from the individual classes (there are several I work with). This uses a modified Kendo interface that has the Excel Export button on the grid.
The revised code includes modifications included in the answer:
rowNumber = 1;
var cellStyle = (XSSFCellStyle)workbook.CreateCellStyle();
cellStyle.WrapText = true;
foreach (var member in members)
{
String value = "";
var aType = member.GetType();
var real = aType.GetProperty(headings[i]);
if (real != null)
{
value = (real.GetValue(member) != null) ? String.Format(format, real.GetValue(member)) : "";
}
var row = sheet.GetRow(rowNumber++);
cell = row.CreateCell(i);
cell.SetCellValue(new XSSFRichTextString(value));
cell.CellStyle = cellStyle;
}
This code now produces the desired result. I also added the XSSRichTextString to the formatting just for good measure.
"CellStyle.WrapText" set After Binding CellStyle ,its working For Me.
Solution:
ICellStyle CellCentertTopAlignment = workbook.CreateCellStyle();
CellCentertTopAlignment = workbook.CreateCellStyle();
CellCentertTopAlignment.SetFont(fontArial16);
CellCentertTopAlignment.Alignment = HorizontalAlignment.Center;
CellCentertTopAlignment.VerticalAlignment = VerticalAlignment.Top;
ICell Row1 = Row1.CreateCell(1);
Row1.SetCellValue(new HSSFRichTextString("I find a solution for this Problem.."));
Row1.CellStyle = CellCentertTopAlignment;
Row1.CellStyle.WrapText = true;
I think you forgot to change the cell's style. You're setting it only on the header.
This:
row.CreateCell(0).SetCellValue(member.FullName);
row.CreateCell(3).SetCellValue(member.endowed_professorship);
Should be something like:
var cell0 = row.CreateCell(0);
cell0.SetCellValue(member.FullName);
cell0.Style = style;
var cell3 = row.CreateCell(3);
cell3.SetCellValue(member.endowed_professorship);
cell3.Style = style;
There's probably a better way of doing this; I'm no NPOI specialist. =)

Office Open XML - Target Cell by its content

How to target Cell if I know its content (there are no duplicates in the xlsx document) using Office Open XML?
I mean I have xlsx sheet (template) and somewhere in it placed my "variable". For example "<<_time>>". I want to find that element (by "variable" name) and change the cell value (current time in this case).
Basic code:
FileInfo newFile = new FileInfo(#"...");
FileInfo template = new FileInfo(#"...");
using (ExcelPackage xlPackage = new ExcelPackage(newFile, template))
{
ExcelWorksheet worksheet = xlPackage.Workbook.Worksheets.First();
//need target Cell by it's value (must use for-loop?)
//worksheet.Cells[...].Value = "...";
xlPackage.Save();
}
Ok, I solved it by classic loop.
var start = worksheet.Dimension.Start;
var end = worksheet.Dimension.End;
for (int row = start.Row; row <= end.Row; row++)
{
for (int col = start.Column; col <= end.Column; col++)
{
string cellValue = worksheet.Cells[row, col].Text.ToString();
if (cellValue == "<<_time>>")
{
worksheet.Cells[row, col].Value = "..";
}
}
}

Create all the rows of a column as a dropdownlist in excel sheet using c#

My requirement is to export a blank excel sheet with 3 columns in which 1st columns of all rows as a dropdownlist, so that user can use this work sheet to modify the data as per their need. I am using c# to exporting file.
I already worked on it but that at the moment, it only creates a dropdown list in a particular cell but I want to make all the rows of first column as a dropdown list .
Below is the code I am using:
object oMissing = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Excel.Application app;
Microsoft.Office.Interop.Excel.Worksheet wksheet;
Microsoft.Office.Interop.Excel.Workbook wkbook;
app = new Microsoft.Office.Interop.Excel.Application();
app.Visible = false;
wkbook = app.Workbooks.Add(true);
wksheet = (Microsoft.Office.Interop.Excel.Worksheet)wkbook.ActiveSheet;
string[] ddl_item =
{
"Answers",
"Autos",
"Finance",
"Games",
"Groups",
"HotJobs",
"Maps",
"Mobile Web",
"Movies",
"Music",
"Personals",
"Real Estate",
"Shopping",
"Sports",
"Tech",
"Travel",
"TV",
"Yellow Pages"
};
Microsoft.Office.Interop.Excel.Range xlsRange;
xlsRange = wksheet.get_Range("A1", "A1");
Microsoft.Office.Interop.Excel.DropDowns xlDropDowns;
Microsoft.Office.Interop.Excel.DropDown xlDropDown;
xlDropDowns = ((Microsoft.Office.Interop.Excel.DropDowns)(wksheet.DropDowns(oMissing)));
xlDropDown = xlDropDowns.Add((double)xlsRange.Left, (double)xlsRange.Top, (double)xlsRange.Width, (double)xlsRange.Height, true);
//Add item into drop down list
for (int i = 0; i < ddl_item.Count(); i++)
{
xlDropDown.AddItem(ddl_item[i], i + 1);
}
app.Visible = true;
i just saw your question, it's a little bit late, but your problem is in your range, you can change your code as this to fulfill your needs:
//change your range
Range range = worksheet.UsedRange;
//this part makes all the in-range rows of first column as a dropdown list
int row;
for (row = 1; row <= range.Rows.Count; row++)
{
xlDropDowns = ((DropDowns) (worksheet.DropDowns(Type.Missing)));
xlDropDown = xlDropDowns.Add((double) range[row, 1].Left, (double) range[row, 1].Top,
(double) range[row, 1].Width, (double) range[row, 1].Height, true);
string[] ddl_item =
{
"Answers",
"Autos",
"Finance",
"Games",
"Groups",
"HotJobs",
"Maps",
"Mobile Web",
"Movies",
"Music",
"Personals",
"Real Estate",
"Shopping",
"Sports",
"Tech",
"Travel",
"TV",
"Yellow Pages"
};
for (int i = 0; i < ddl_item.Count(); i++)
{
xlDropDown.AddItem(ddl_item[i], i + 1);
}
}

Categories