Reputation: 11
I am trying to export a datatable that I filled from a query, however I am getting an exception with the message "Invalid cell value" at the last line.
This only seems to happen when the column contains null values. How can I modify my datatable to replace the null values with a string or write the null value in the Excel file, as a blank space.
This is the code that I have:
DataSet ds = new DataSet("New_DataSet");
DataTable dt = new DataTable("New_DataTable");
ds.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
dt.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
OracleDataAdapter adptr = new OracleDataAdapter();
try {
con.Open();
var oracmd = con.CreateCommand();
oracmd.CommandText = "select Column1,Column2 from Test";
adptr.SelectCommand = oracmd;
adptr.Fill(dt);
con.Close();
ds.Tables.Add(dt);
SaveFileDialog saveFileDialog1 = new SaveFileDialog
{
Filter = "Excell files (*.xls)|*.xls";
RestoreDirectory = true;
};
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
ExcelLibrary.DataSetHelper.CreateWorkbook(saveFileDialog1.FileName, ds);
Upvotes: 1
Views: 1202
Reputation: 2764
i use this method in order to check a DataSet
for null valuse and replace them:
public static DataSet DBNull(DataSet dataSet)
{
try
{
foreach (DataTable dataTable in dataSet.Tables)
foreach (DataRow dataRow in dataTable.Rows)
foreach (DataColumn dataColumn in dataTable.Columns)
if (dataRow.IsNull(dataColumn))
{
if (dataColumn.DataType.IsValueType) dataRow[dataColumn] = Activator.CreateInstance(dataColumn.DataType);
else if (dataColumn.DataType == typeof(bool)) dataRow[dataColumn] = false;
else if (dataColumn.DataType == typeof(Guid)) dataRow[dataColumn] = Guid.Empty;
else if (dataColumn.DataType == typeof(string)) dataRow[dataColumn] = string.Empty;
else if (dataColumn.DataType == typeof(DateTime)) dataRow[dataColumn] = DateTime.MaxValue;
else if (dataColumn.DataType == typeof(int) || dataColumn.DataType == typeof(byte) || dataColumn.DataType == typeof(short) || dataColumn.DataType == typeof(long) || dataColumn.DataType == typeof(float) || dataColumn.DataType == typeof(double)) dataRow[dataColumn] = 0;
else dataRow[dataColumn] = null;
}
return dataSet;
}
catch (Exception ex)
{
return dataSet;
}
}
Upvotes: 0