我不好意思对不起 在我的Windows应用程序中,我有一个带有数据的gridview,在这里我想将gridview导出到excel,我正在尝试下面的代码 我的代码将dataGridView导出到excel工作表时出现问题,我得到了这样的结果(???%$ ^&$$&$%&$%^ $ @%#@%@#%)
我希望有人能帮助我提供该代码
我搜索了很多次却没有找到答案
不知道将表设置为什么排序规则。是否可以正确导出数据或将其转换为正确的编码?
导出按钮
private void Btexport_Click(object sender, EventArgs e)
{
if (dataGridView1.Rows.Count > 0)
{
try
{
// Bind Grid Data to Datatable
DataTable dt = new DataTable();
foreach (DataGridViewColumn col in dataGridView1.Columns)
{
dt.Columns.Add(col.HeaderText, col.ValueType);
}
int count = 0;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (count < dataGridView1.Rows.Count - 1)
{
dt.Rows.Add();
foreach (DataGridViewCell cell in row.Cells)
{
dt.Rows[dt.Rows.Count - 1][cell.ColumnIndex] = cell.Value.ToString();
}
}
count++;
}
// Bind table data to Stream Writer to export data to respective folder
StreamWriter wr = new StreamWriter(@"C:\Users\ils\Desktop\New folder (2)\Book1.xls");
// Write Columns to excel file
for (int i = 0; i < dt.Columns.Count; i++)
{
wr.Write(dt.Columns[i].ToString().ToUpper() + "\t");
}
wr.WriteLine();
//write rows to excel file
for (int i = 0; i < (dt.Rows.Count); i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
if (dt.Rows[i][j] != null)
{
wr.Write(Convert.ToString(dt.Rows[i][j]) + "\t");
}
else
{
wr.Write("\t");
}
}
wr.WriteLine();
}
wr.Close();
}
catch (Exception ex)
{
throw ex;
}
}
}
数据
public void Disp_data()
{
SqlConnection mycon = new SqlConnection("Data Source=DESKTOP-J7D5POF;Initial Catalog=ilswork;Persist Security Info=True;User ID=test;Password=12345;Connect Timeout=60");
mycon.Open();
SqlCommand cmd = mycon.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select name1 from [dbo].[test5]";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
mycon.Close();
}
private void Form3_Load(object sender, EventArgs e)
{
Disp_data();
}
}