I am creating an excel file using
Microsoft.Office.Interop.Excel;
and filling up the excel sheet using the data from database(SQLite).
All things are working perfectly,only problem is that the data inside the cell
is like
1001 1002 1003 1004
1 6/15/2018 3:34:20 101 <---><---><---><---> -->Leaving the extra space here.
can anyone please found out what is the problem with code causing these?
What I have tried:
public void ExportToExcel()
{
DirectoryInfo di = System.IO.Directory.CreateDirectory("C:\\ProgramData\\tthhSensorCalibrator");
string logFilename = System.IO.Path.Combine(Environment.GetFolderPath(
Environment.SpecialFolder.CommonApplicationData), di + "\\databaseFile.db3");
System.Data.SQLite.SQLiteConnection con = new System.Data.SQLite.SQLiteConnection(@"Data source="+ logFilename);
System.Data.SQLite.SQLiteCommand com = new System.Data.SQLite.SQLiteCommand(con);
com.CommandText = "Select * FROM Log";
int i = 0;
int j = 0;
string data = null;
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
SQLiteDataAdapter dscmd = new SQLiteDataAdapter(com.CommandText, con);
DataSet ds = new DataSet();
dscmd.Fill(ds);
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
for (j = 0; j <= ds.Tables[0].Columns.Count - 1; j++)
{
data = ds.Tables[0].Rows[i].ItemArray[j].ToString();
xlWorkSheet.Cells[i + 1, j + 1] = data;
}
}
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.InitialDirectory = @"Documents\";
saveFileDialog1.Title = "Save text Files";
saveFileDialog1.DefaultExt = "txt";
saveFileDialog1.Filter = "Excel files (*.xls)|*.xls";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
string filename="";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
filename = saveFileDialog1.FileName;
}
xlWorkBook.SaveAs(filename, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
MessageBox.Show("Excel file created");
void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
}
}