因此,在它具有worbook.saveAs()之前,它无法工作。但是我需要它来打开一个现有文件,然后保存它。不用写了。
我尝试使用此处不同问题中显示的方法,但是所有这些方法都在替换当前文件并创建一个新文件。
SqlConnection cnn;
string connectionString = null;
string sql = null;
string data = null;
int i = 0;
int j = 0;
string filename = @"D:\ExcelFiles\DatabaseComp.xls";
Microsoft.Office.Interop.Excel.Application xlApp;
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlApp = new Microsoft.Office.Interop.Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(filename, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue);
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
connectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Diether\Desktop\OJT KIOSK\DB_Kiosk.mdf;Integrated Security=True;User Instance=True";
cnn = new SqlConnection(connectionString);
cnn.Open();
sql = "SELECT * FROM TBL_Company";
SqlDataAdapter dscmd = new SqlDataAdapter(sql, cnn);
DataSet ds = new DataSet();
dscmd.Fill(ds);
foreach (dynamic worksheet in xlWorkBook.Worksheets)
{
xlWorkSheet.Cells.ClearContents();
}
foreach (System.Data.DataTable dt in ds.Tables)
{
for (int i1 = 0; i1 < dt.Columns.Count; i1++)
{
xlWorkSheet.Cells[1, i1 + 1] = dt.Columns[i1].ColumnName;
}
}
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
int s = i + 1;
for (j = 0; j <= ds.Tables[0].Columns.Count - 1; j++)
{
data = ds.Tables[0].Rows[i].ItemArray[j].ToString();
xlWorkSheet.Cells[s + 1, j + 1] = data;
}
}
xlApp.DisplayAlerts = false;
xlWorkBook.Save();
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
xlApp.DisplayAlerts = false;
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);