wimformエクスポートデータexcel
データバージョン2をエクスポートして、個人的に方法を簡略化して、しかもテストに合格して、しかしクリックしてキャンセルする時まだはっきりしていないで、親、待っています.の
参照:
//データベース接続---グローバルSqlConnection conn=new SqlConnection(ConfigurationManagement.ConnectionStrings["Loginthree].ToString();
参照:
//データベース接続---グローバルSqlConnection conn=new SqlConnection(ConfigurationManagement.ConnectionStrings["Loginthree].ToString();
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
//
string sqlall = "select * from Student";
DataTable dat = testone(sqlall);
printAll(dat);
}
testone() : /// <summary>
///
/// </summary>
/// <param name="sql"></param>
/// <returns>DataTable</returns>
private DataTable testone(string sqlall)
{
try
{
conn.Open();
dapter = new SqlDataAdapter(sqlall,conn);
// , DataSet SQL Server 。 。
SqlCommandBuilder scb = new SqlCommandBuilder(dapter);
ds = new DataSet();
dapter.Fill(ds);// dapter.Fill(ds, "class");//DataTable customerTable = dtc["Product"];
return ds.Tables[0];
}
catch(Exception e)
{
Console.WriteLine("{0} Exception caught.", e);
}
finally
{
conn.Close();
}
return null ;
}
printAllメソッド:
/// <summary>
/// excel
/// </summary>
/// <param name="dt"></param>
public void printAll(System.Data.DataTable dt)
{
// execl
//
if (dt.Rows.Count == 0)
return;
// Excel.Application
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
// Excel.Application excel = new Excel.Application();
// ,Workbook , , Application , false
Microsoft.Office.Interop.Excel.Workbook xls_book = excel.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
excel.Visible = true;
try
{
// , true Excel,
excel.Visible = false;
// Excel
for (int i = 0; i < dt.Columns.Count; i++)
{
excel.Cells[1, i + 1] = dagvtwo.Columns[i].HeaderText;// DataGridView
}
// DataGridView Excel
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
string str = dt.Rows[i][j].ToString();
excel.Cells[i + 2, j + 1] = "'" + str;
}
}
}
//
excel.DisplayAlerts = false;
excel.AlertBeforeOverwriting = false;
// , false
excel.Application.Workbooks.Add(true).Save();
// excel
excel.Save("D:\\KKHMD.xls");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, " ");
}
finally
{
// Excel
excel.Quit();
excel = null;
}
}