如何将.net中DataGridView中的数据导出到Excel文本(是在windows窗体中)
2个回答
展开全部
private void button2_Click(object sender, EventArgs e)
{
string strconn = "Data Source=JUKINB-SERVER;Initial Catalog=TxData;Persist Security Info=True;User ID=sa";
SqlConnection conn = new SqlConnection(strconn);
string strcom = "select * from fzje";
SqlDataAdapter sqlda = new SqlDataAdapter(strcom, conn);
DataSet sqlds = new DataSet();
sqlda.Fill(sqlds, "table1");
sqlds.Tables["table1"].AcceptChanges();
this.Cursor = Cursors.WaitCursor;
Excel.Application myExcel = new Excel.Application();
myExcel.Application.Workbooks.Add(true);
myExcel.Visible = true;
//Object Date[ds.Tables["CurrentTable"].Rows.Count][ds.Tables["CurrentTable"].Columns.Count];
//生成标题
for (int i = 0; i < sqlds.Tables["table1"].Columns.Count; i++)
{
myExcel.Cells[2, i + 1] = sqlds.Tables["table1"].Columns[i].Caption;
}
//填充数据
for (int i = 0; i < sqlds.Tables["table1"].Rows.Count; i++)
{
for (int j = 0; j < sqlds.Tables["table1"].Columns.Count; j++)
{
if (sqlds.Tables["table1"].Rows[i][j].GetType() == typeof(System.String))
{
myExcel.Cells[i + 3, j + 1] = "'" + sqlds.Tables["table1"].Rows[i][j].ToString();
}
else
{
myExcel.Cells[i + 3, j + 1] = sqlds.Tables["table1"].Rows[i][j].ToString();
}
}
}
this.Cursor = Cursors.Default;
MessageBox.Show("导出成功! ", "恭喜", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
}
连接字符串自己改一下,这个方法可能速度不是很高!
{
string strconn = "Data Source=JUKINB-SERVER;Initial Catalog=TxData;Persist Security Info=True;User ID=sa";
SqlConnection conn = new SqlConnection(strconn);
string strcom = "select * from fzje";
SqlDataAdapter sqlda = new SqlDataAdapter(strcom, conn);
DataSet sqlds = new DataSet();
sqlda.Fill(sqlds, "table1");
sqlds.Tables["table1"].AcceptChanges();
this.Cursor = Cursors.WaitCursor;
Excel.Application myExcel = new Excel.Application();
myExcel.Application.Workbooks.Add(true);
myExcel.Visible = true;
//Object Date[ds.Tables["CurrentTable"].Rows.Count][ds.Tables["CurrentTable"].Columns.Count];
//生成标题
for (int i = 0; i < sqlds.Tables["table1"].Columns.Count; i++)
{
myExcel.Cells[2, i + 1] = sqlds.Tables["table1"].Columns[i].Caption;
}
//填充数据
for (int i = 0; i < sqlds.Tables["table1"].Rows.Count; i++)
{
for (int j = 0; j < sqlds.Tables["table1"].Columns.Count; j++)
{
if (sqlds.Tables["table1"].Rows[i][j].GetType() == typeof(System.String))
{
myExcel.Cells[i + 3, j + 1] = "'" + sqlds.Tables["table1"].Rows[i][j].ToString();
}
else
{
myExcel.Cells[i + 3, j + 1] = sqlds.Tables["table1"].Rows[i][j].ToString();
}
}
}
this.Cursor = Cursors.Default;
MessageBox.Show("导出成功! ", "恭喜", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
}
连接字符串自己改一下,这个方法可能速度不是很高!
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询