Handle Null Value In Gridview During Exporting To Excel - excel

I am working with a C# Windows application. Trying to export data from gridview to Excel , but when the gridview column is empty I do get error message.
How to handle that? Please help
This is my code
// Store Header from Gridview to Excel
for (int i = 1; i < dgvresult.Columns.Count + 1; i++)
{
Excel.Cells[1, i] = dgvresult.Columns[i - 1].HeaderText;
}
// Loop rows and columns of Gridview to store to Excel
for (int i = 0; i < dgvresult.Rows.Count; i++)
{
for (int j = 0; j < dgvresult.Columns.Count; j++)
{
Excel.Cells[i + 2, j + 1] = dgvresult.Rows[i].Cells[j].Value.ToString(); // Here when the value in Gridview is empty error how to handle this
}
}
Excel.ActiveWorkbook.SaveCopyAs("D:\\Asserts.xls");
Excel.ActiveWorkbook.Saved = true;
Excel.Quit();
MessageBox.Show("Excel file created,you can find the file D:\\Asserts.xls");
Excel.Visible = true;

Found solution do a checking by code below
private void btnexport_Click(object sender, EventArgs e)
{
Microsoft.Office.Interop.Excel.ApplicationClass Excel = new Microsoft.Office.Interop.Excel.ApplicationClass();
Excel.Application.Workbooks.Add(Type.Missing);
Excel.Columns.ColumnWidth = 14;
// Store Header from Gridview to Excel
for (int i = 1; i < dgvresult.Columns.Count + 1; i++)
{
Excel.Cells[1, i] = dgvresult.Columns[i - 1].HeaderText;
}
// Loop rows and columns of Gridview to store to Excel
for (int i = 0; i < dgvresult.Rows.Count; i++)
{
for (int j = 0; j < dgvresult.Columns.Count; j++)
{
if (dgvresult.Rows[i].Cells[j].Value == null)
{
dgvresult.Rows[i].Cells[j].Value = "NA"; // Where the gridview is empty do a checking and Insert NA
}
Excel.Cells[i + 2, j + 1] = dgvresult.Rows[i].Cells[j].Value.ToString();
}
}
Excel.ActiveWorkbook.SaveCopyAs("D:\\Asserts.xls");
Excel.ActiveWorkbook.Saved = true;
Excel.Quit();
MessageBox.Show("Excel file created,you can find the file D:\\Asserts.xls");
Excel.Visible = true;
}

Related

The ExcelPackage object does not return sheets

I am trying to upload an excel file to a hosted Blazor webassembly application, for which I am using the following code:
string path= #"D:\Otros\LibrosExcel\ReferenciasDotación.xls";
FileInfo fileInfo = new FileInfo(path);
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
using (ExcelPackage excelPackage = new OfficeOpenXml.ExcelPackage(fileInfo))
{
//loop all worksheets
ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.FirstOrDefault();
//loop all rows
for (int i = 1; i <= worksheet.Dimension.End.Row; i++)
{
//loop all columns in a row
for (int j = 1; j <= worksheet.Dimension.End.Column; j++)
{
//add the cell data to the List
if (worksheet.Cells[i, j].Value != null)
{
excelData.Add(worksheet.Cells[i, j].Value.ToString());
}
}
}
}
return excelData;
but the line of code
ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.FirstOrDefault ();
returns null

Create a table in powerpoint with Apache poi

I'm using Java v8 and "org.apache.poi" and "poi-ooxml" (both are version 3.9). I'm trying to create a powerpoint with a slide on it which contains a table.
I can get the powerpoint file to create ok but the slide is empty but for a small black box in the top right corner. I'm guessing I'm missing something small but can't see what it is. I've tried some examples from the web and they look to be the same as what I'm seeing.
This is what I see in the Powerpoint slide:
My code is as below:
XMLSlideShow powerpoint = new XMLSlideShow();
XSLFSlide slide = powerpoint.createSlide();
XSLFTable table = slide.createTable();
table.setAnchor(new Rectangle(50, 50, 800, 800));
int numColumns = 3;
int numRows = 5;
XSLFTableRow headerRow = table.addRow();
headerRow.setHeight(50);
// header
for (int i = 0; i < numColumns; i++) {
XSLFTableCell th = headerRow.addCell();
XSLFTextParagraph p = th.addNewTextParagraph();
p.setTextAlign(TextAlign.CENTER);
XSLFTextRun r = p.addNewTextRun();
r.setText("Header " + (i + 1));
r.setFontSize(20);
r.setFontColor(Color.white);
th.setFillColor(new Color(79, 129, 189));
table.setColumnWidth(i, 150);
}
// rows
for (int rownum = 0; rownum < numRows; rownum++) {
XSLFTableRow tr = table.addRow();
tr.setHeight(50);
// header
for (int i = 0; i < numColumns; i++) {
XSLFTableCell cell = tr.addCell();
XSLFTextParagraph p = cell.addNewTextParagraph();
XSLFTextRun r = p.addNewTextRun();
r.setText("Cell " + (i + 1));
if (rownum % 2 == 0) {
cell.setFillColor(new Color(208, 216, 232));
}
else {
cell.setFillColor(new Color(233, 247, 244));
}
}
}
try {
try (FileOutputStream out = new FileOutputStream("c:\\myFile.pptx"))
{
try {
powerpoint.write(out);
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
Any thoughts/guidance would be really appreciated.
Thanks Ro

reading Excel with ClosedXML

What would be the most efficient way to read an entire Excel file using ClosedXML and returning List<List<object>> ?
This somehow doesn't give me data. I get empty lists.
var wb = new XLWorkbook(finalFilePath);
var ws = wb.Worksheets.First();
var range = ws.RangeUsed();
var colCount = range.ColumnCount();
var rowCount = range.RowCount();
var i = 1;
var j = 1;
List<List<object>> data = new List<List<object>>();
while (i < rowCount + 1)
{
List<object> row = new List<object>();
while (j < colCount + 1)
{
row.Add(ws.Cell(i, j).Value);
j++;
}
data.Add(row);
i++;
}
This gets the job done:
Dictionary<Tuple<int, int>, object> data = new Dictionary<Tuple<int, int>, object>();
using (XLWorkbook wb = new XLWorkbook(filePath))
{
var ws = wb.Worksheets.First();
var range = ws.RangeUsed();
for (int i = 1; i < range.RowCount() + 1; i++)
{
for (int j = 1; j < range.ColumnCount() + 1; j++)
{
data.Add(new Tuple<int, int>(i,j), ws.Cell(i,j).Value);
}
}
}

Work at Primefaces Extensions Custom Exporter

I have some dataTables on the web page and I'd like to export all to an excel file, like the web page images:
I'd like to export the footer like showed in page. I try to use rendered and exportable,both with boolean attribute, but no way.
What might be the reason of such behaviour?
I use the customExport, doing the steps on the link Steps to Custom Exporter
When I debug the code, I see the mode to create the footers on the document exporter, which it's not consist the tag exportable (isExportable()). Into the method "tableColumnGroup(Sheet sheet, DataTable table, String facetType){", of the class ExcelCustomExporter, I need to add an if: "if(column.isExportable()){" to create a cell and add value to this, and another if, the same way, to increment the variable using in the method for(i++); only the if is true I create the cell, add value and increment the variable i.
See below the code modified:
protected void tableColumnGroup(Sheet sheet, DataTable table, String facetType) {
ColumnGroup cg = table.getColumnGroup(facetType);
List<UIComponent> headerComponentList = null;
if (cg != null) {
headerComponentList = cg.getChildren();
}
if (headerComponentList != null) {
for (UIComponent component : headerComponentList) {
if (component instanceof org.primefaces.component.row.Row) {
org.primefaces.component.row.Row row = (org.primefaces.component.row.Row) component;
int sheetRowIndex = sheet.getLastRowNum() + 1;
Row xlRow = sheet.createRow(sheetRowIndex);
int i = 0;
for (UIComponent rowComponent : row.getChildren()) {
UIColumn column = (UIColumn) rowComponent;
String value = null;
if (facetType.equalsIgnoreCase("header")) {
value = column.getHeaderText();
} else {
value = column.getFooterText();
}
int rowSpan = column.getRowspan();
int colSpan = column.getColspan();
Cell cell = xlRow.getCell(i);
if (rowSpan > 1 || colSpan > 1) {
if (rowSpan > 1) {
cell = xlRow.createCell((short) i);
Boolean rowSpanFlag = false;
for (int j = 0; j < sheet.getNumMergedRegions(); j++) {
CellRangeAddress merged = sheet.getMergedRegion(j);
if (merged.isInRange(sheetRowIndex, i)) {
rowSpanFlag = true;
}
}
if (!rowSpanFlag) {
cell.setCellValue(value);
cell.setCellStyle(facetStyle);
sheet.addMergedRegion(new CellRangeAddress(
sheetRowIndex, //first row (0-based)
sheetRowIndex + (rowSpan - 1), //last row (0-based)
i, //first column (0-based)
i //last column (0-based)
));
}
}
if (colSpan > 1) {
cell = xlRow.createCell((short) i);
for (int j = 0; j < sheet.getNumMergedRegions(); j++) {
CellRangeAddress merged = sheet.getMergedRegion(j);
if (merged.isInRange(sheetRowIndex, i)) {
cell = xlRow.createCell((short) ++i);
}
}
cell.setCellValue(value);
cell.setCellStyle(facetStyle);
sheet.addMergedRegion(new CellRangeAddress(
sheetRowIndex, //first row (0-based)
sheetRowIndex, //last row (0-based)
i, //first column (0-based)
i + (colSpan - 1) //last column (0-based)
));
i = i + colSpan - 1;
}
} else {
//TODO TRATAR E VERIRIFICAR SE O VALUE PODE SER EXIBIDO
if (column.isExportable()) {
cell = xlRow.createCell((short) i);
for (int j = 0; j < sheet.getNumMergedRegions(); j++) {
CellRangeAddress merged = sheet.getMergedRegion(j);
if (merged.isInRange(sheetRowIndex, i)) {
cell = xlRow.createCell((short) ++i);
}
}
cell.setCellValue(value);
cell.setCellStyle(facetStyle);
}
}
if (column.isExportable()) {
i++;
}
}
}
}
}
Screnshoot, but the JAN to MAY:

Generating a HTML table from an Excel file using EPPlus?

I would like to generate a HTML table from an excel file. The EPPlus package provides a .net API for manipulating excel file. I would be happy to know whether it is possible to generate a HTML table code from an Excel file using EPPlus? I couldn't find anything on the documentation, but intuition tells me that there should be a way to do it
Thank you!
If you are looking for something built into EPPlus, I havent seen anything that will export directly HTML.
Best thing would be to bring in the Excel file to EPPlus and extract the data to a collection or DataTable. That should be pretty straight forward.
From there, there is plenty of documentation on how to get that to an html table. Quick search turned up this as the first hit:
Datatable to html Table
I wrote some code, you can try this.
static void Main(string[] args)
{
ExcelPackage p = new ExcelPackage(new System.IO.FileInfo("X.XLSX"));
var sheet = p.Workbook.Worksheets["HMTD"];
var noOfCol = sheet.Dimension.End.Column;
var noOfRow = sheet.Dimension.End.Row;
StringBuilder s = new StringBuilder();
s.Append("<table>");
for (int i = 1; i < noOfRow; i++)
{
s.Append("<tr>");
for (int j = 1; j < noOfCol; j++)
{
int colspan = 1;
int rowspan = 1;
if (!sheet.Cells[i, j].Merge || (sheet.Cells[i, j].Merge && isFirstMergeRange(sheet, sheet.Cells[i, j].Address, ref colspan, ref rowspan)))
{
s.Append("<td rowspan='" + rowspan + "' colspan='" + colspan + "'>");
if(sheet.Cells[i,j] != null && sheet.Cells[i,j].Value != null)
s.Append(sheet.Cells[i,j].Value.ToString());
s.Append("</td>");
}
}
s.Append("</tr>");
}
s.Append("</table>");
System.IO.File.WriteAllText("duc.html",s.ToString());
Console.ReadKey();
}
private static bool isFirstMergeRange(ExcelWorksheet sheet, string address, ref int colspan, ref int rowspan)
{
colspan = 1;
rowspan = 1;
foreach (var item in sheet.MergedCells)
{
var s = item.Split(':');
if (s.Length > 0 && s[0].Equals(address)){
ExcelRange range = sheet.Cells[item];
colspan = range.End.Column - range.Start.Column;
rowspan = range.End.Row - range.Start.Row;
if(colspan == 0) colspan = 1;
if(rowspan == 0) rowspan = 1;
return true;
}
}
return false;
}
Based on the answer from Duc Tran Minh, it works fine for me after I modified the code like this:
static void Main(string[] args)
{
ExcelPackage p = new ExcelPackage(new System.IO.FileInfo("X.XLSX"));
var sheet = p.Workbook.Worksheets["HMTD"];
var noOfCol = sheet.Dimension.End.Column;
var noOfRow = sheet.Dimension.End.Row;
StringBuilder s = new StringBuilder();
s.Append("<table>");
for (int i = 1; i <= noOfRow; i++)
{
s.Append("<tr>");
for (int j = 1; j <= noOfCol; j++)
{
int colspan = 1;
int rowspan = 1;
if (!sheet.Cells[i, j].Merge || (sheet.Cells[i, j].Merge && isFirstMergeRange(sheet, sheet.Cells[i, j].Address, ref colspan, ref rowspan)))
{
s.Append("<td rowspan='" + rowspan + "' colspan='" + colspan + "'>");
if(sheet.Cells[i,j] != null && sheet.Cells[i,j].Value != null)
s.Append(sheet.Cells[i,j].Value.ToString());
s.Append("</td>");
}
}
s.Append("</tr>");
}
s.Append("</table>");
System.IO.File.WriteAllText("duc.html",s.ToString());
Console.ReadKey();
}
bool isFirstMergeRange(ExcelWorksheet sheet, string address, ref int colspan, ref int rowspan)
{
colspan = 1;
rowspan = 1;
foreach (var item in sheet.MergedCells)
{
var s = item.Split(':');
if (s.Length > 0 && s[0].Equals(address))
{
ExcelRange range = sheet.Cells[item];
colspan = range.End.Column - range.Start.Column + 1;
rowspan = range.End.Row - range.Start.Row + 1;
return true;
}
}
return false;
}

Resources