I am trying to save the data table values into excel. I have a Load Report button from which I am getting data into a grid view.
Load Report Button Code
private void BtnInvHD_Click(object sender, EventArgs e)
{
string dir = #"C:\Output\Log\HavingDuesLog";
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
string location = Path.Combine(dir, "HavingDues_log_"+name+"_" + DateTime.Now.ToString("dd-MM-yy_hh:mm:ss") + ".xls");
string cs = LoginForm.cs;
date = dtPicker.Value.ToString("yyyy-MM-dd");
if (cnn.State == ConnectionState.Closed)
{
cnn.Open();
}
sqlCmd = new SqlCommand("RptIV030", cnn);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("#DateFrom", date);
SqlDataAdapter sqlSda = new SqlDataAdapter(sqlCmd);
sqlSda.Fill(dtData);
dGInvHD.DataSource = dtData;
writeExcelFile(location,dtData);
btnExport.Enabled = true;
//return dtData;
}
Write to Excel Function
public void writeExcelFile(string location, DataTable read)
{
//Create excel app object
Microsoft.Office.Interop.Excel.Application xlSamp = new Microsoft.Office.Interop.Excel.Application();
if (xlSamp == null)
{
MessageBox.Show("Excel is Not Installed");
//Console.WriteLine("Excel is not Insatalled");
//Console.ReadKey();
return;
}
//Create a new excel book and sheet
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlWorkBook = xlSamp.Workbooks.Add(misValue);
// get the reference of first sheet.
// store its reference to worksheet
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet = xlWorkBook.ActiveSheet;
// changing the name of active sheet
xlWorkSheet.Name = "Having Dues-" + name + "-Till-" + date;
// column headings
for (var i = 0; i < read.Columns.Count; i++)
{
xlWorkSheet.Cells[1, i + 1] = read.Columns[i].ColumnName;
}
// rows
for (var i = 0; i < read.Rows.Count; i++)
{
// to do: format datetime values before printing
for (var j = 0; j < read.Columns.Count; j++)
{
xlWorkSheet.Cells[i + 2, j + 1] = read.Rows[i][j];
}
}
//Save the opened excel book to custom location
//Dont forget, you have to add to exist location
xlWorkBook.SaveAs(location, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue,
Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlSamp.Quit();
//release Excel Object
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlSamp);
xlSamp = null;
}
catch (Exception ex)
{
xlSamp = null;
MessageBox.Show(ex.ToString());
}
finally
{
GC.Collect();
}
}
When I execute my code am I able to view data into gridview but unable to write it into an excel file.
I am getting error at xlWorkBook.SaveAs(location, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
Error Message
The file could not be accessed. Try one of the following:
Make sure the specified folder exists.
Make sure the folder that contains the file is not read-only.
Make sure the filename and folder path do not contain any of the following characters: < > ? [ ] : | or *
Make sure the filename and folder path do not contain more than 218 characters.
Any help would be highly appreciated.
Use something Like this I think its useful:
xlSamp.ActiveWorkbook.SaveAs(filepath, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
xlSamp.ActiveWorkbook.Close(true, missing, missing);
xlSamp.Quit();
Make sure the filename and folder path do not contain more than 218 characters.
This error comes when your location path will be to long reduce path
Make sure the specified folder exists.
Make sure the folder that contains the file is not read-only.
Make sure your location folder must exists on that location and give
read write permission to that folder
Make sure the filename and folder path do not contain any of the following characters: < > ? [ ] : | or *
give folder name and filename proper format
Related
I have wrote the following code for exporting my local database data to an excel file. The fact is that it is working properly, but I'd only like to export it with the actual date, or just month, like august, or something like that. Besides that, the problem that really matters is that it replaces every time the previously exported excel file. How can I change this thing? Thanks !
private void button3_Click_1(object sender, EventArgs e)
{
var connString = (#"Data Source=" + System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)) + #"\Angajati.sdf");
using (var conn = new SqlCeConnection(connString))
{
try
{
conn.Open();
var query = "SELECT * FROM info ";
var command = new SqlCeCommand(query, conn);
var dataAdapter = new SqlCeDataAdapter(command);
var dataTable = new DataTable();
dataAdapter.Fill(dataTable);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
Int16 i, j;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
for (i = 0; i <= dataGridView1.RowCount - 2; i++)
{
for (j = 0; j <= dataGridView1.ColumnCount - 1; j++)
{
xlWorkSheet.Cells[i + 2, j + 1] = dataGridView1[j, i].Value.ToString();
}
}
//adds column names to excel
string[] colNames = new string[dataGridView1.Columns.Count];
int col = 0;
foreach (DataGridViewColumn dc in dataGridView1.Columns)
colNames[col++] = dc.HeaderText;
char lastColumn = (char)(65 + dataGridView1.Columns.Count - 1);
xlWorkSheet.get_Range("A1", lastColumn + "1").Value2 = colNames;
xlWorkSheet.get_Range("A1", lastColumn + "1").Font.Bold = true;
xlWorkSheet.get_Range("A1", lastColumn + "1").VerticalAlignment
= Excel.XlVAlign.xlVAlignCenter;
xlWorkBook.SaveAs(#"C:\Users\Andrei\Documents\Visual Studio 2010\Projects\Stellwag\Stellwag\db.xls", 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("Salvat cu succes");
}
private 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();
}
}
If you don't want it to overwrite the same workbook every time then you'll need to specify a different file name rather than hard coding it in.
Something simple like creating the filename with the current datetime would normally be sufficient (you can change the format to suit you):
string fileName = #"db " + DateTime.Now.ToString("dd-MM-yyyy HH-mm-ss") + #".xls";
string filePath = Path.Combine(#"C:\Users\Andrei\Documents\Visual Studio 2010\Projects\Stellwag\Stellwag", fileName);
xlWorkBook.SaveAs(filePath, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
This would produce a file like this:
db 01-09-2015 10-32-35.xls
There is still not explicit check to see if the file exists, but unless you're clicking it every second it's unlikely to overwrite.
My small console tool tries to read an excel file and create new out of that depending on set criteria.
Problem: When there is a filename conflict(file already exists with same name), programme should generate the file with an unique name. But now a message comes up with "yes/no/cancel" message box to save the file. If user clicks NO then exception thrown. The message is as follows:
A file named 'D:\sample.xls' already exists in this location. Do you want to replace it?
The exception:
A first chance exception of type 'System.Runtime.InteropServices.COMException' occurred in ExcelSplitter.exe
Additional information: Exception from HRESULT: 0x800A03EC
The following line thorws the exception
xlWorkBook.SaveAs(fileName, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
The code is as follows:
private bool WriteToExcel(String fileName, List<RowEntity> headerRowObj, List<RowEntity> dataRowObj)
{
Excel.Application xlApp;
Excel.Workbook xlWorkBook = null;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
int headerRowTotal = 0;
for (int i = 0; i < headerRowObj.Count; i++)
{
for (int j = 0; j < headerRowObj[i].ColumnValues.Count; j++)
{
xlWorkSheet.Cells[i + 1, j + 1] = headerRowObj[i].ColumnValues[j].ToString();
}
headerRowTotal++;
}
for (int i = 0; i < dataRowObj.Count; i++)
{
for (int j = 0; j < dataRowObj[i].ColumnValues.Count; j++)
{
xlWorkSheet.Cells[headerRowTotal + i + 1, j + 1] = dataRowObj[i].ColumnValues[j].ToString();
}
}
if (IsExcelFileOpen(xlWorkBook))
{
errorList.Add(Error.GetError(-7));
return false;
}
else
{
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);
return true;
}
The above method is called in the following method:
private int SeparateExcleFiles(int headerLines, int groupOnColumn, string outputPath, string inputFile, FileEntity fileObj, RowEntity rowObj)
{
List<RowEntity> headerRowObj = fileObj.RowValues.GetRange(0, headerLines);
if (rowObj.ColumnValues.Count < groupOnColumn)
{
errorList.Add(Error.GetError(-6));
return -6;
}
else
{
var dataRows = fileObj.RowValues.GetRange(headerLines, fileObj.RowValues.Count - (headerLines)).GroupBy(re => re.ColumnValues[groupOnColumn - 1]).ToList();
for (int i = 0; i < dataRows.Count; i++)
{
var fileName = String.Format("{0}-{1}{2}", Path.GetFileNameWithoutExtension(inputFile), dataRows[i].Key.ToString(), Path.GetExtension(inputFile));
var filePath = Path.Combine(outputPath, fileName);
if (File.Exists(filePath))
{
fileName = GetUniqueFilename(fileName);
}
if (WriteToExcel(filePath, headerRowObj, dataRows[i].ToList() as List<RowEntity>))
{
System.Console.WriteLine("Wrote {0}", fileName);
}
}
return 0;
}
}
private bool IsExcelFileOpen(Workbook wBook)
{
Excel.Application exApp;
exApp = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
try
{
exApp.Workbooks.get_Item(wBook);
return true;
}
catch (Exception)
{
return false;
}
}
Where exactly am I doing it wrong?
Could you try this on the saveas part.
try
{
xlWorkBook.SaveAs(fileName, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
}
catch(Exception e)
{
//BLANK (do nothing)
}
This will allow you to handle the exception, but if you don't want to do anything and just not overwrite just leave the handling process blank.
Having the exception handler will let the system think that you acknowledged the event and will let the program continue.
I have a web page in ASP.NET C# that opens an Excel file with Microsoft.Office.Interop.Excel classes.
The excel file has VBA code that runs on the Workbook_BeforeClose event.
When opening and closing the file with Excel, the code runs fine, with a prompt to save the changes after the code is run.
But when doing the same on the webpage with C#, the page just loads indefenitly. Debugging shows that it stops(waits?) at the line myExcelWorkbook.Close(true);
Here is what the C# code looks like:
using Excel = Microsoft.Office.Interop.Excel;
public string getExcelInfo(string value1, string value2, string mapPath)
{
Excel.Application myExcelApp;
Excel.Workbooks myExcelWorkbooks;
Excel.Workbook myExcelWorkbook;
object misValue = System.Reflection.Missing.Value;
myExcelApp = new Excel.Application();
myExcelWorkbooks = myExcelApp.Workbooks;
//Copy file to allow simultaneous executions
Random rnd = new Random();
int rand = rnd.Next(1000000);
File.Copy(mapPath+"/App_Data/ConfigAQNX01.xlsm", mapPath+"/App_Data/ConfigAQNX01"+rand.ToString() + ".xlsm");
//Open file, workbook and sheet
String fileName = mapPath+"/App_Data/ConfigAQNX01" + rand.ToString() + ".xlsm";
myExcelWorkbook = myExcelWorkbooks.Open(fileName, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue);
Excel.Worksheet myExcelWorksheet = (Excel.Worksheet)myExcelWorkbook.ActiveSheet;
//insert values
myExcelWorksheet.Cells[3, 2] = value1;
myExcelWorksheet.Cells[6, 2] = value2;
//Save so formulaes are executed
myExcelWorkbook.Save();
myExcelWorksheet = (Excel.Worksheet)myExcelWorkbook.ActiveSheet;
//read value in excel
Excel.Range currentRange = (Excel.Range)myExcelWorksheet.Cells[7, 4];
string Cost_Cad_Unit = currentRange.Value2.ToString();
//Close Excel
GC.Collect();
GC.WaitForPendingFinalizers();
Marshal.ReleaseComObject(currentRange);
Marshal.ReleaseComObject(myExcelWorksheet);
//Set SaveChange to true on close
myExcelWorkbook.Close(true); //This line is where processing takes forever, literraly
Marshal.ReleaseComObject(myExcelWorkbook);
Marshal.ReleaseComObject(myExcelWorkbooks);
myExcelApp.Quit();
Marshal.ReleaseComObject(myExcelApp);
currentRange = null;
myExcelWorksheet = null;
myExcelWorkbook = null;
myExcelWorkbooks = null;
myExcelApp = null;
return Cost_Cad_Unit;
}
Are there options that can be set to get the VBA code to run, or ways to know what makes it hang? Or are there limitations with Microsoft.Office.Interop.Excel to get Workbook_BeforeClose code to run?
Thank you,
Here is the VBA code:
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Dim FileName, CalcSheet As String
Dim English As Boolean
Worksheets("Drawing").Activate
Worksheets("Drawing OE").Activate
Worksheets("Interface").Activate
Worksheets("Parameters").Range("Closing").Formula = "O"
If Worksheets("Parameters").Range("CreateDrawing").Value = "N" Then Exit Sub
If Worksheets("Interface").Range("digit_oper").Value = 4 Then
Sheets(Array("Drawing", "Drawing OE")).Select
Else
Sheets(Array("Drawing")).Select
End If
Worksheets("Drawing").Activate
FileName = ActiveSheet.Range("Drawingpdf").Value
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=FileName, _
Quality:=xlQualityStandard, IncludeDocProperties:=False, _
IgnorePrintAreas:=False, OpenAfterPublish:=False
Worksheets("Calc").Activate
FileName = ActiveSheet.Range("Calcpdf").Value
English = Worksheets("Drawing").Range("English").Value
If English Then CalcSheet = "Calc EN" Else CalcSheet = "Calc"
Sheets(Array(CalcSheet)).Select
Worksheets(CalcSheet).Activate
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=FileName, _
Quality:=xlQualityStandard, IncludeDocProperties:=False, _
IgnorePrintAreas:=False, OpenAfterPublish:=False
Worksheets("Parameters").Range("Closing").Formula = "N"
Worksheets("Interface").Activate
End Sub
I created a new method, GenerateFiles(), moved the code from Workbook_BeforeClose to this method and changing the C# code to :
...
myExcelWorkbook.Save();
myExcelApp.Run("GenerateFiles");
myExcelWorkbook.Close(false);
...
Now works.
It's as if myExcelWorkbook.Close creates an infinite loop with Workbook_BeforeClose when the Workbook_BeforeClose method doesn't execute "fast enough"...
I am exporting multiple datatable as different worksheets to a single excel file and it is working fine. However, the excel file is saved to the path specified. I want a save as dialog from where the user can select the path to save the file. I have tried the following code on button click:
protected void excelexport(object sender, EventArgs e)
{
try
{
string sql = null;
string data = null;
string path = "C:\\inetpub/wwwroot/MahindraEarth/exportexcel/exportexcel";
int i = 0;
int j = 0;
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
xlApp = new Excel.ApplicationClass();
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Add(misValue);
System.Data.DataTable dt = new System.Data.DataTable();
System.Data.DataTable dts = new System.Data.DataTable(); ;
System.Data.DataTable dss = new System.Data.DataTable();
Enquiry gs = new Enquiry();
ResultClass objres = gs.fn_GetEnquiryList();
if (objres.bStatus)
{
eslist<Enquiry> OBJLIST = objres.objData as eslist<Enquiry>;
if (OBJLIST.Count > 0)
{
dt = (DataTable)OBJLIST;
}
}
Operator op = new Operator();
ResultClass objrest = op.fn_GetOperatorList();
if (objrest.bStatus)
{
eslist<Operator> OBJLISTS = objrest.objData as eslist<Operator>;
if (OBJLISTS.Count > 0)
{
dts = (DataTable)OBJLISTS;
}
}
Contact co = new Contact();
ResultClass objress = co.fn_GetContactList();
if (objress.bStatus)
{
eslist<Contact> OBJLISS = objress.objData as eslist<Contact>;
if (OBJLISS.Count > 0)
{
dss = (DataTable)OBJLISS;
}
}
DataSet dataSet = new DataSet();
dataSet.Tables.Add(dt);
dataSet.Tables.Add(dts);
dataSet.Tables.Add(dss);
SaveFileDialog saveFileDialog = new SaveFileDialog();
String[] Worksheets = new String[dataSet.Tables.Count];
Excel.Worksheet[] xlWorkSheet = new Excel.Worksheet[dataSet.Tables.Count];
for (int k = 0; k < dataSet.Tables.Count; k++)
{
DataTable dst = dataSet.Tables[k];
xlWorkSheet[k] = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(k + 1);
for (i = 0; i <= dst.Rows.Count - 1; i++)
{
for (j = 0; j <= dst.Columns.Count - 1; j++)
{
xlWorkSheet[k].Cells[1, j + 1] = dataSet.Tables[k].Columns[j].ColumnName;
data = dst.Rows[i].ItemArray[j].ToString();
xlWorkSheet[k].Cells[i + 2, j + 1] = data;
xlWorkSheet[k].Name = dataSet.Tables[k].TableName;
}
}
}
xlWorkBook.SaveAs(path + ".xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
for (int p = 0; p < 3; p++)
{
releaseObject(xlWorkSheet[p]);
}
releaseObject(xlWorkBook);
releaseObject(xlApp);
exportsuccess.Style.Add("display", "");
}
catch (Exception ex)
{
}
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
}
finally
{
GC.Collect();
}
}
How to get the save as dialog box in order to save the multiple datatables in multiple worksheet and not as a single sheet.
Thanks,
give this a try. This should give you the Save As dialog box. Some of the code should look similar to yours, which should give you an idea as to where this code excerpt should be attached.
#region Save & Quit
//Save and quit, use SaveCopyAs since SaveAs does not always work
Guid id = Guid.NewGuid();
string uniqueFileName = id.ToString() + ".xls";
string fileName = Server.MapPath("~/" + uniqueFileName);
xlApp.DisplayAlerts = false; //Supress overwrite request
xlWorkBook.SaveAs(fileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
//Release objects
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
//Give the user the option to save the copy of the file anywhere they desire
String FilePath = Server.MapPath("~/" + uniqueFileName);
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "application/vnd.ms-excel";
response.AddHeader("Content-Disposition", "attachment; filename=MyClaimsReport-" + DateTime.Now.ToShortDateString() + ".xls;");
response.TransmitFile(FilePath);
response.Flush();
response.Close();
//Delete the temporary file
DeleteFile(fileName);
#endregion
private void DeleteFile(string fileName)
{
if (File.Exists(fileName))
{
try
{
File.Delete(fileName);
}
catch (Exception ex)
{
//Could not delete the file, wait and try again
try
{
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
File.Delete(fileName);
}
catch
{
//Could not delete the file still
}
}
}
}
I am trying to export query result sets into an excel sheet. I need to run 8 queries, each of which will be a different sheet in the excel file. I also need to add a bit of formatting around the sheet (adding a header, making the report look nice, etc).
Currently, my code is just running a single query (so only a single sheet of data). This takes a LONG time to fill out 4000 rows with 7 columns and thats a tiny sample. Is there are better way to do this? Thanks so much!
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
string data = null;
int i = 0;
int j = 0;
xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
string cs = "oracle connection string filtered for online posting";
DataSet ds = new DataSet();
OracleConnection oconn = new OracleConnection(cs);
oconn.Open();
Model_Netstat netstat = new Model_Netstat();
OracleCommand oc = new OracleCommand(netstat.queryNetstatAll(session.caseName), oconn);
oc.CommandType = CommandType.Text;
OracleDataAdapter oda = new OracleDataAdapter(oc);
try
{
oda.Fill(ds);
} catch(Exception ex)
{
Console.Write(ex.Message);
}
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;
}
}
xlWorkBook.SaveAs("test.xls", 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);
Check the free OpenXML SDK 2 from Microsoft out, it does what you need without automation and that's much faster and is usable in ASP.NET too (automation is not supported there)...