NPOI Excel Format not working - c#

I have a function that is generating an Excel file using the NPOI Library. Witch for the most part is working fine just got a problem with style's they seem to function dodgy. Currently my focus is the number formats:
I would like all decimals to display as: 12.156.235,33 for example
According to the reserach on google the format that should do that should be: "#,##0.00" but the value shows up as: 12156235,33 and the cell type is set to general instead of number
It also looks like alot of people have problems with this. Hope there is a solution cos everything else I whanted to do I managed with the NPOI library and would not whant to switch now.
The procedure:
IDataFormat dataFormat;
public string GenerateExcel(ExcelData data)
{
var dateFormat = dataFormat.GetFormat("dd.MM.yyyy HH:mm:ss");
var decimalFormat = dataFormat.GetFormat("#,##0.00");
string xlsPath, xlsFile, xlsName;
xlsPath = Environment.GetEnvironmentVariable("TEMP");
xlsName = Path.GetRandomFileName().Replace(".", ""); //DateTime.Now.ToString("yyyy-MM-dd");
xlsName += ".xlsx";
xlsFile = Path.Combine(xlsPath, xlsName);
if (File.Exists(xlsFile))
File.Delete(xlsFile);
workbook = new XSSFWorkbook();
dataFormat = workbook.CreateDataFormat();
XSSFCellStyle style = (XSSFCellStyle)workbook.CreateCellStyle();
NPOI.SS.UserModel.ICell cell;
Dictionary<int, int> maxColSize = new Dictionary<int, int>();
string title;
int rr;
foreach (var sheet in data.Sheets)
{
maxColSize.Clear();
if(sheet.Hidden != null)
foreach (var h in sheet.Hidden)
{
sheet.HideRow(h);
}
worksheet = (XSSFSheet)workbook.CreateSheet(sheet.Title);
rr = 0;
if (sheet.Titles!=null && sheet.Titles.Length > 0)
{
worksheet.CreateRow(rr);
rr++;
for (int t = 0; t < sheet.Titles.Length; t++)
{
title = (string)sheet.Titles[t].Title;
maxColSize.Add(t, title.Length);
cell = worksheet.GetRow(0).CreateCell(t, NPOI.SS.UserModel.CellType.String);
cell.SetCellValue(title);
if (sheet.Titles[t].Style != null)
cell.CellStyle = GetCellStyle(sheet.Titles[t].Style);
}
}
int cols = 0;
int cc = 0;
IRow row = null;
for (int r = 0; r < sheet.Rows.Length; r++)
{
if (sheet.Rows[r].row > -1)
{
rr = sheet.Rows[r].row;
row = worksheet.GetRow(sheet.Rows[r].row);
}
else
{
//rr = r;
row = worksheet.GetRow(rr);
}
if (row == null)
{
row = worksheet.CreateRow(rr);
}
if(sheet.Rows[r].Cells.Length > cols)
cols = sheet.Rows[r].Cells.Length;
for (int c = 0; c < sheet.Rows[r].Cells.Length;c++ )
{
cc = c;
if (sheet.Rows[r].Cells[c].column > -1)
{
cc = sheet.Rows[r].Cells[c].column;
}
if (!maxColSize.Keys.Contains(cc))
maxColSize.Add(cc, 0);
switch (sheet.Rows[r].Cells[c].DataType)
{
case "DateTime":
cell = row.CreateCell(cc, NPOI.SS.UserModel.CellType.Numeric);
cell.SetCellValue((DateTime)sheet.Rows[r].Cells[c].Value);
cell.CellStyle.DataFormat = dateFormat;
if (maxColSize[cc] < cell.NumericCellValue.ToString().Length)
maxColSize[cc] = cell.NumericCellValue.ToString().Length;
break;
case "Numeric":
case "Decimal":
cell = row.CreateCell(cc, NPOI.SS.UserModel.CellType.Numeric);
cell.SetCellValue(Convert.ToDouble(sheet.Rows[r].Cells[c].Value)); //sheet.Rows[r].Cells[c].Value
cell.CellStyle.DataFormat = decimalFormat;
if (maxColSize[cc] < cell.NumericCellValue.ToString().Length)
maxColSize[cc] = cell.NumericCellValue.ToString().Length;
break;
case "Integer":
cell = row.CreateCell(cc, NPOI.SS.UserModel.CellType.Numeric);
cell.SetCellValue(Convert.ToInt32(sheet.Rows[r].Cells[c].Value));
cell.CellStyle.DataFormat = dataFormat.GetFormat("0");
if (maxColSize[cc] < cell.NumericCellValue.ToString().Length)
maxColSize[cc] = cell.NumericCellValue.ToString().Length;
break;
case "Date":
cell = row.CreateCell(cc, NPOI.SS.UserModel.CellType.Numeric);
cell.SetCellValue((DateTime)sheet.Rows[r].Cells[c].Value);
cell.CellStyle.DataFormat = dataFormat.GetFormat("dd.MM.yyyy");
if (maxColSize[cc] < cell.NumericCellValue.ToString().Length)
maxColSize[cc] = cell.NumericCellValue.ToString().Length;
break;
case "Boolean":
cell = row.CreateCell(cc, NPOI.SS.UserModel.CellType.Boolean);
cell.SetCellValue(Convert.ToBoolean(sheet.Rows[r].Cells[c].Value));
if (maxColSize[cc] < cell.BooleanCellValue.ToString().Length)
maxColSize[cc] = cell.StringCellValue.ToString().Length;
break;
case "Formula":
cell = row.CreateCell(cc, NPOI.SS.UserModel.CellType.Formula);
cell.SetCellFormula((string)(sheet.Rows[r].Cells[c].Value));
if (maxColSize[cc] < cell.BooleanCellValue.ToString().Length)
maxColSize[cc] = cell.StringCellValue.ToString().Length;
break;
default:
cell = row.CreateCell(cc, NPOI.SS.UserModel.CellType.String);
cell.SetCellValue((string)sheet.Rows[r].Cells[c].Value);
if (maxColSize[cc] < cell.StringCellValue.Length)
maxColSize[cc] = cell.StringCellValue.Length;
break;
}
if (sheet.Rows[r].Cells[c].Style != null)
{
var st = GetCellStyle(sheet.Rows[r].Cells[c].Style);
cell.CellStyle = st;
}
}
if (sheet.Rows[r].row == -1)
rr++;
if(sheet.Merge != null)
foreach (var merge in sheet.Merge)
{
worksheet.AddMergedRegion( new NPOI.SS.Util.CellRangeAddress(merge.FirstRow,merge.LastRow, merge.FirstColumn, merge.LastColumn));
}
}
foreach (var col in maxColSize)
{
worksheet.SetColumnWidth(col.Key, ((int)(col.Value * 1.14388)) * 256);
}
XSSFFormulaEvaluator.EvaluateAllFormulaCells(workbook);
}
using (var fs = new FileStream(xlsFile, FileMode.Create, FileAccess.Write))
{
workbook.Write(fs);
}
return xlsFile;
}

Related

Invalid index exception with Excel Interop

I make to get data excel with C# winform.
private void ReleaseExcelObject(object obj)
{
try
{
if (obj != null)
{
Marshal.ReleaseComObject(obj);
obj = null;
}
}
catch (Exception ex)
{
obj = null;
throw ex;
}
}
private void buttonOpen_Click(object sender, EventArgs e)
{
Microsoft.Office.Interop.Excel.Application application = null;
Workbook workBook = null;
int tempNum = 0;
try
{
OpenFileDialog dlg = new OpenFileDialog();
if (dlg.ShowDialog() != DialogResult.OK)
return;
application = new Microsoft.Office.Interop.Excel.Application();
application.Visible = true;
workBook = application.Workbooks.Open(dlg.FileName);
Worksheet newWorkSheet = workBook.Worksheets.Add(After: workBook.Worksheets.Item[workBook.Worksheets.Count]);
int newSheetRow = 0;
Dictionary<int, string> upData = new Dictionary<int, string>();
for (int sheetIndex = 1; sheetIndex<workBook.Worksheets.Count; sheetIndex++)
{
for (int row = 1; row < workBook.Worksheets[sheetIndex].UsedRange.Rows.Count; row++)
{
upData.Add(row, null);
for (int col = 1; col < workBook.Worksheets[sheetIndex].UsedRange.Columns.Count; col++)
{
tempNum++;
if (workBook.Worksheets[sheetIndex].Cells[col, row] != null)
{
string cellData = workBook.Worksheets[sheetIndex].Cells[col, row].value;
string[] datas = cellData.Split(' ');
string dataName = null;
for (int k = 1; k < datas.Length; k++)
{
dataName += datas[k];
}
string icd11 = datas[0];
newWorkSheet.Cells[newSheetRow,0] = icd11;
newWorkSheet.Cells[newSheetRow,1] = dataName;
newWorkSheet.Cells[newSheetRow,2] = upData[col - 1];
upData[col] = dataName;
continue;
}
}
}
}
}
catch (Exception exc)
{
MessageBox.Show(tempNum + exc.Message);
}
finally
{
ReleaseExcelObject(workBook);
ReleaseExcelObject(application);
}
}
The part where the error occurs is
MessageBox.Show(workBook.Sheets[0].ToString());
this part.
And force workBookSheet.getitem("hardCording").
If you do this, an error occurs in the part of direct data access of the cell.
I wonder how I can query and insert excel data.
The error is Invalid index. (Exception from HRESULT: 0x8002000B (DISP_E_BADINDEX))
Excel data:
edit sheet[0]
sheet[0] is not able
i don't understand VBA
how to implement this
excel treeExample
Worksheet newWorkSheet = workBook.Worksheets.Add(After: workBook.Worksheets.Item[workBook.Worksheets.Count]);
int newSheetRow = 1;
Dictionary<int, string> upData = new Dictionary<int, string>();
for (int sheetIndex = 1; sheetIndex<workBook.Worksheets.Count; sheetIndex++)
{
int rowMax=workBook.Worksheets[sheetIndex].UsedRange.Rows.Count;
int colMax = workBook.Worksheets[sheetIndex].UsedRange.Columns.Count;
for (int i = 0; i < workBook.Worksheets[sheetIndex].UsedRange.Rows.Count; i++)
upData.Add(i, "000000");
for (int row = 1; row < workBook.Worksheets[sheetIndex].UsedRange.Rows.Count; row++)
{
for (int col = 1; col < workBook.Worksheets[sheetIndex].UsedRange.Columns.Count; col++)
{
tempRow = row;
tempCol = col;
if (workBook.Worksheets[sheetIndex].Cells[row, col] != null)
{
Range cell = workBook.Worksheets[sheetIndex].Cells[row, col];
string cellData = cell.Value;
if (cellData != null)
{
string[] datas = cellData.Split(null);
string dataName = null;
for (int k = 1; k < datas.Length; k++)
{
dataName += datas[k];
}
string icd11 = datas[0];
Range newCellData1 = newWorkSheet.Cells[newSheetRow, 1];
newCellData1.Value = icd11;
Range newCellData2 = newWorkSheet.Cells[newSheetRow, 2];
newCellData2.Value = dataName;
Range newCellData3 = newWorkSheet.Cells[newSheetRow, 3];
newCellData3.Value = upData[col - 1];
upData[col] = datas[0];
newSheetRow++;
}
continue;
}
}
}
upData.Clear();
}
}
excel debug is not work in visual studio
I fixed the bugs in my code.
cell. value and these sub-items are not visible

Upload Excel file whose column data is dateTime but C# could not figure out NPOI

My Excel has column data like
When I get the data in my asp.net api using below code, I get the data 01-1月-2021 instead of 2021-01-01 then I get the error in line entity.startTime = Convert.ToDateTime(row[0].ToString().Trim());
for (int j = 0; j < HttpContext.Current.Request.Files.Count; j++)
{
string fileName = HttpContext.Current.Request.Files[j].FileName;
if (fileName.Contains(".xlsx") || fileName.Contains(".xls"))
{
dataset = ExcelHelper.ExcelStreamToDataSet(HttpContext.Current.Request.Files[j].InputStream, HttpContext.Current.Request.Files[j].FileName);
bool isFileFind = false;
List<ExcelRowErrorInfoAssetInfo> fileErrorAllList = new List<ExcelRowErrorInfoAssetInfo>();
for (int i = 0; i < dataset.Tables.Count; i++)
{
DataTable table = dataset.Tables[i];
string sheetName = table.TableName;
#region
for (int r = 0; r < table.Rows.Count; r++)
{
DataRow row = table.Rows[r];
int cnt = row.ItemArray.ToList().Where(a => string.IsNullOrEmpty(a.ToString())).Count();
if (cnt < row.ItemArray.Count())
{
if (sheetName == "基本信息")
{
AssetsInfoMap entity = new AssetsInfoMap();
//startTime is type of DateTime
entity.startTime = Convert.ToDateTime(row[0].ToString().Trim());
entity.endTime = Convert.ToDateTime(row[1].ToString().Trim());
}
}
}
#endregion
}
public static DataSet ExcelStreamToDataSet(Stream stream, string fileName)
{
DataSet dataset = new DataSet();
int startRow = 0;
try
{
IWorkbook workbook = null;
if (fileName.IndexOf(".xlsx") > 0)
workbook = new XSSFWorkbook(stream);
else if (fileName.IndexOf(".xls") > 0)
workbook = new HSSFWorkbook(stream);
int sheetCount=workbook.NumberOfSheets;
for (int m = 0; m < sheetCount-1; m++)
{
DataTable data = new DataTable();
ISheet sheet = workbook.GetSheetAt(m);
data.TableName= sheet.SheetName;
if (sheet != null)
{
IRow firstRow = sheet.GetRow(0);
int cellCount = firstRow.LastCellNum;
for (int k = firstRow.FirstCellNum; k < cellCount; ++k)
{
ICell cell = firstRow.GetCell(k);
if (cell != null)
{
string cellValue = cell.StringCellValue;
if (cellValue != null)
{
DataColumn column = new DataColumn(cellValue);
data.Columns.Add(column);
}
}
}
startRow = sheet.FirstRowNum + 1;
int rowCount = sheet.LastRowNum;
for (int i = startRow; i <= rowCount; ++i)
{
IRow row = sheet.GetRow(i);
if (row == null) continue;
DataRow dataRow = data.NewRow();
for (int j = row.FirstCellNum; j < cellCount; ++j)
{
if (row.GetCell(j) != null)
dataRow[j] = row.GetCell(j).ToString();
}
data.Rows.Add(dataRow);
}
}
dataset.Tables.Add(data);
}
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex.Message);
}
return dataset;
}
}
So how to get correct data to assign it to my model, do you have any ideas based on my above code?
ICell defines a property .DateCellValue, so you should use this when mapping your date values:
ICell cell = row.GetCell(j);
if (cell.CellType == CellType.Numeric && DateUtil.IsCellDateFormatted(cell))
{
dataRow[j] = cell.DateCellValue;
}
This will now store your value as a DateTime rather than as a string. We now need to do away with your DateTime->string->DateTime conversion:
entity.startTime = (DateTime)row[0];

C#: cannot convert string to string [] []

I have a question regarding my code. The situation is the following: I am working with many arrays with data, all of same length. Then I want to build a second version with specific camps.
I have the following code:
string[][][] cuentasHFMPreFinal = new string[nroCuenta.Length][][];
string anoCubo = "'2019";
string escenarioCubo = "Control";
string versionCubo = "Version Vigente";
for (int i = 0, j = 0, k = 0; i < nroCuenta.Length && j < nroCuenta.Length && k < nroCuenta.Length; i++, j++, k++){
cuentasHFMPreFinal[i] = anoCubo;
}
The idea would be to give specific values to the new array (which will have more dimensions, this is a brief example). End array would end as something like:
cuentasHFM [anoCubo][escenarioCubo][versionCubo][....][lastVar]
The error is on the cuentasHFMPreFinal[i] = anoCubo part, giving the error on title.
Full code is:
static void Main(string[] args)
{
//-----------------------------------------------------------------------
//ARCHIVO CUENTAS AUTOMATICAS
//obtener direccion de archivo
string pathCuentasAuto = #"C:\DescargaHFM\data\cuentas_auto.txt";
pathCuentasAuto = Path.GetFullPath(pathCuentasAuto);
//leer lineas archivo y pasar a arreglo
string[] cuentasAuto = File.ReadAllLines(pathCuentasAuto);
//-----------------------------------------------------------------------
//ARCHIVO HFM CHILE
//obtener direccion de archivo
string pathHFM = #"C:\DescargaHFM\data\HFM.txt";
pathHFM = Path.GetFullPath(pathHFM);
//leer lineas archivo y pasar a arreglo
string[] hfm = File.ReadAllLines(pathHFM);
//obtener separador tab
string separadorTab = "\t";
//separar lineas por separadores
string[][] camposHFM = new string[hfm.Length][];
for (int i = 0; i < hfm.Length; i++) {
camposHFM[i] = hfm[i].Split(separadorTab.ToCharArray());
}
//arreglo con periodo(meses)
string[] mesesHFM = new string[camposHFM.Length];
for (int i = 0; i < camposHFM.Length; i++)
{
string mesPeriodo = camposHFM[i][0];
switch (mesPeriodo){
case "Per01":
mesPeriodo = "Jan";
break;
case "Per02":
mesPeriodo = "Feb";
break;
case "Per03":
mesPeriodo = "Mar";
break;
case "Per04":
mesPeriodo = "Apr";
break;
case "Per05":
mesPeriodo = "May";
break;
case "Per06":
mesPeriodo = "Jun";
break;
case "Per07":
mesPeriodo = "Jul";
break;
case "Per08":
mesPeriodo = "Aug";
break;
case "Per09":
mesPeriodo = "Sep";
break;
case "Per10":
mesPeriodo = "Oct";
break;
case "Per11":
mesPeriodo = "Nov";
break;
case "Per12":
mesPeriodo = "Dec";
break;
}
mesesHFM[i] = mesPeriodo;
}
//otener cantidad total y cantidad gl
double[] QTotalUSGAP = new double[hfm.Length];
double[] QTotalGL = new double[hfm.Length];
double[] QTotalResta = new double[hfm.Length];
for (int i = 0; i < camposHFM.Length; i++) {
QTotalUSGAP[i] = Double.Parse(camposHFM[i][3]);
QTotalGL[i] = Double.Parse(camposHFM[i][4]);
QTotalResta[i] = QTotalUSGAP[i] - QTotalGL[i];
}
//obtener numero cuenta
string[] nroCuenta = new string[hfm.Length];
/*Formula Excel:
*SI(IZQUIERDA(C2;4)="ACCT";MED(C2;5;LARGO(C2)-3);IZQUIERDA(C2;ENCONTRAR("_";C2)-1))
*/
for (int i = 0; i < camposHFM.Length; i++) {
nroCuenta[i] = camposHFM[i][2];
if (nroCuenta[i].Substring(0, 4) == "ACCT") {
nroCuenta[i] = nroCuenta[i].Substring(5, (nroCuenta[i].Length - 3));
}
else {
//int indexFind = nroCuenta[i].IndexOf('_');
//nroCuenta[i] = nroCuenta[i].Substring(0, (indexFind - 1));
nroCuenta[i] = nroCuenta[i].Substring(0, nroCuenta[i].Length);
}
}
//comprobar existencia de nroCuenta en cuentasAuto
string[] existeNroCuenta = new string[nroCuenta.Length];
for (int i = 0; i < nroCuenta.Length; i++){
if (cuentasAuto.Contains(nroCuenta[i])){
existeNroCuenta[i] = "TRUE";
}
else{
existeNroCuenta[i] = "FALSE";
}
}
//armar arreglo pre final
string[][][] cuentasHFMPreFinal = new string[nroCuenta.Length][][];
string anoCubo = "'2019";
string escenarioCubo = "Control";
string versionCubo = "Version Vigente";
string monedaCubo = "CLP";
string ubgCubo = "Generico UBG";
string ajusteICCubo = "Ajuste 99";
string organizacionCubo = "Generico";
for (int i = 0, j = 0, k = 0; i < nroCuenta.Length && j < nroCuenta.Length && k < nroCuenta.Length; i++, j++, k++){
cuentasHFMPreFinal[i] = anoCubo;
}
}
Use classes, structs or tuples to achieve what you're trying to achieve.

C# EPPlus not evaluating formula SUM(A3:B3)

I have just started working with EPPlus. i have data table which has some numeric data and formula. when i load data table by EPPlus and save to excel then formula not evaluated i found when i open the same excel file. formula lies in excel cell as string like SUM(A3:B3)
To evaluate formulate i have tried many options of EPPLUS and those are listed here
pack.Workbook.Worksheets["Test"].Calculate();
pack.Workbook.Worksheets["Test"].Cells["A3"].Calculate();
pack.Workbook.Worksheets["Test"].Cells["B3"].Calculate();
ws.Calculate();
Here i am referring my full sample code where formula not working. please have a look and tell me what i need to add in my code to evaluate formula.
private void button1_Click(object sender, EventArgs e)
{
DataTable dt = GetDataTable();
string path = #"d:\EPPLUS_DT_Excel.xlsx";
Stream stream = File.Create(path);
using (ExcelPackage pack = new ExcelPackage())
{
ExcelWorksheet ws = pack.Workbook.Worksheets.Add("Test");
ws.Cells["A1"].LoadFromDataTable(dt, false);
//pack.Workbook.Worksheets["Test"].Calculate();
//pack.Workbook.Worksheets["Test"].Cells["A3"].Calculate();
//pack.Workbook.Worksheets["Test"].Cells["B3"].Calculate();
ws.Calculate();
pack.SaveAs(stream);
stream.Close();
MessageBox.Show("Done");
}
}
public DataTable GetDataTable()
{
string strSum = "", strColName, strImmediateOneUp = "", strImmediateTwoUp = "";
int startsum = 0;
int currow = 0;
bool firstTimeSum = true;
int NumRows = 3;
int NumColumns = 2;
DataTable dt = new DataTable();
for (int col = 0; col < NumColumns; col++)
{
strColName = GenerateColumnText(col);
DataColumn datacol = new DataColumn(strColName, typeof(object));
dt.Columns.Add(datacol);
}
for (int row = 0; row < NumRows; row++)
{
dt.Rows.Add();
for (int col = 0; col < NumColumns; col++)
{
if (row < 2)
{
dt.Rows[row][col] = Convert.ToInt32(new Random().Next(1, NumRows));
}
else
{
if (firstTimeSum)
{
if (row - currow == 2)
{
currow = row;
startsum = 0;
firstTimeSum = false;
}
else
{
startsum = 1;
}
}
else
{
if (row - currow == 3)
{
currow = row;
startsum = 0;
}
}
if (startsum == 0)
{
strColName = GenerateColumnText(col);
strImmediateOneUp = strColName + ((row + 1) - 1).ToString();
strImmediateTwoUp = strColName + ((row + 1) - 2).ToString();
strSum = string.Format("+SUM({0}:{1})", strImmediateTwoUp, strImmediateOneUp);
dt.Rows[row][col] = strSum;
}
else
{
dt.Rows[row][col] = Convert.ToInt32(new Random().Next(1, NumRows));
}
}
}
startsum = 1;
}
return dt;
}
private string GenerateColumnText(int num)
{
string str = "";
char achar;
int mod;
while (true)
{
mod = (num % 26) + 65;
num = (int)(num / 26);
achar = (char)mod;
str = achar + str;
if (num > 0) num--;
else if (num == 0) break;
}
return str;
}
When adding a formula to a cell you use the Formula property. When you load a range from a DataTable using LoadFromDataTable it has no way of knowing that some of the values are meant to be interpreted as formulas.
You can use LoadDataTable to populate the cells on which the formulas will operate, but for the formulas you'll need to set the Formula property.

Office Open XMl SDK Writing Numbers to Sheet

I am trying wo write Numbers from a DataTable to an Datasheet - unfortunately, this does not work as expected, e. g. the DataSheet is corrupted.
I am using the following code:
private void AddDataToSheet(ExcelViewData data, SheetData sheetData)
{
var excelData = data.WriteableDataTable;
// this returns a datatable
// the numbers have a format like "8,1" "8,0" etc.
for (int i = 0; i < excelData.Rows.Count; i++)
{
Row row = new Row();
//row.RowIndex = (UInt32)i;
for (int c = 0; c < excelData.Columns.Count; c++)
{
Cell cell = new Cell();
CellValue cellvalue = new CellValue();
//cell.CellReference = SharedMethods.GetExcelColumnName(i + 1) + (c + 1).ToString();
cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.Number;
cellvalue.Text = excelData.Rows[i][c].ToString().Replace(",",".");
cell.Append(cellvalue);
row.Append(cell);
}
sheetData.Append(row);
}
}
Any Idea why this fails? I have seem multiple tutorials with the same approach.
Try out this method:
public void InsertDataTableIntoExcel(SpreadsheetDocument _excelDoc, SheetData SheetData, DataTable excelData, int rowIndex = 1)
{
if (_excelDoc != null && SheetData != null)
{
if (excelData.Rows.Count > 0)
{
try
{
uint lastRowIndex = (uint)rowIndex;
for (int row = 0; row < excelData.Rows.Count; row++)
{
Row dataRow = GetRow(lastRowIndex, true);
for (int col = 0; col < excelData.Columns.Count; col++)
{
Cell cell = GetCell(dataRow, col + 1, lastRowIndex);
string objDataType = excelData.Rows[row][col].GetType().ToString();
//Add text to text cell
if (objDataType.Contains(TypeCode.Int32.ToString()) || objDataType.Contains(TypeCode.Int64.ToString()) || objDataType.Contains(TypeCode.Decimal.ToString()))
{
cell.DataType = new EnumValue<CellValues>(CellValues.Number);
cell.CellValue = new CellValue(objData.ToString());
}
else
{
cell.CellValue = new CellValue(objData.ToString());
cell.DataType = new EnumValue<CellValues>(CellValues.String);
}
}
lastRowIndex++;
}
}
catch (OpenXmlPackageException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
}
else
{
OpenXmlPackageException openEx = new OpenXmlPackageException("No data from datatable");
throw openEx;
}
}
else
{
OpenXmlPackageException openEx = new OpenXmlPackageException("Workbook not found");
throw openEx;
}
}

Categories

Resources