我正在将数据从sql server数据库导出到wpf中的excel,并且我已经成功实现了该功能。现在我想在将生成的excel保存到某个位置后自动打开它。有任何想法吗?提前致谢。我想要的功能就像屏幕截图中的那样:
private void button1_Click(object sender, RoutedEventArgs e)
{
string sql = null;
string data = null;
// string path = null;
//string myfilename = "Report";
int i = 0;
int j = 0;
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.ApplicationClass();
xlApp = new Microsoft.Office.Interop.Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet.Name = "Customer List";
//connectionString = "data source=servername;initial catalog=databasename;user id=username;password=password;";
//SqlConnection cnn = new SqlConnection(GetConnectionString());
SqlConnection cnn = new SqlConnection();
cnn.ConnectionString = @"Data Source=.\sqlexpress;Initial Catalog=ClientLists;Integrated Security=SSPI;";
cnn.Open();
sql = "select FirstName, LastName, City, PostCode, TelephoneNo from Customers";
SqlDataAdapter dscmd = new SqlDataAdapter(sql, cnn);
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 + 2, j + 1] = data;
}
}
xlWorkSheet.Cells.ColumnWidth = 16;
xlWorkSheet.Cells.Font.Size = 12;
xlWorkSheet.Cells[1, 1].Font.Bold = true;
xlWorkSheet.Cells[1, 2].Font.Bold = true;
xlWorkSheet.Cells[1, 3].Font.Bold = true;
xlWorkSheet.Cells[1, 4].Font.Bold = true;
xlWorkSheet.Cells[1, 5].Font.Bold = true;
xlWorkSheet.Cells[1, 1].Font.Color = Microsoft.Office.Interop.Excel.XlRgbColor.rgbBlue;
xlWorkSheet.Cells[1, 2].Font.Color = Microsoft.Office.Interop.Excel.XlRgbColor.rgbBlue;
xlWorkSheet.Cells[1, 3].Font.Color = Microsoft.Office.Interop.Excel.XlRgbColor.rgbBlue;
xlWorkSheet.Cells[1, 4].Font.Color = Microsoft.Office.Interop.Excel.XlRgbColor.rgbBlue;
xlWorkSheet.Cells[1, 5].Font.Color = Microsoft.Office.Interop.Excel.XlRgbColor.rgbBlue;
xlWorkSheet.Cells[1, 1] = "First Name";
xlWorkSheet.Cells[1, 2] = "Last Name";
xlWorkSheet.Cells[1, 3] = "City";
xlWorkSheet.Cells[1, 4] = "Post Code";
xlWorkSheet.Cells[1, 5] = "Telephone NO";
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
}
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();
}
}
}
}