怎么把C#窗体的DataGridView数据导出到xls格式文件?

2024-11-14 11:34:21
推荐回答(2个)
回答1:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;using System.Data.SqlClient;
namespace Case07_5
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} SqlConnection sqlcon = new SqlConnection("server=(local);user id=myzf;pwd=123456;database=SQL_Data"); //定义SqlConnection对象实例并连接数据库
SqlDataAdapter myda; //定义SqlDataAdapter对象实例
DataSet myds; //定义DataSet对象实例 public bool ExportDataGridview(DataGridView dgv, bool isShowExcle)
{
if (dgv.Rows.Count == 0)
return false;
//建立Excel对象
Excel.Application excel = new Excel.Application();
excel.Application.Workbooks.Add(true);
excel.Visible = isShowExcle;
//生成字段名称
for (int i = 0; i < dgv.ColumnCount; i++)
{
excel.Cells[1, i + 1] = dgv.Columns[i].HeaderText;
}
//填充数据
for (int i = 0; i < dgv.RowCount - 1; i++)
{
for (int j = 0; j < dgv.ColumnCount; j++)
{
if (dgv[j, i].ValueType == typeof(string))
{
excel.Cells[i + 2, j + 1] = "'" + dgv[j, i].Value.ToString();
}
else
{
excel.Cells[i + 2, j + 1] = dgv[j, i].Value.ToString();
}
}
}
return true;
}
private void button1_Click(object sender, EventArgs e)
{
//调用自定义函数ExportDataGridview
ExportDataGridview(dataGridView1, true);
} private void Form1_Load(object sender, EventArgs e)
{
myda = new SqlDataAdapter("select * from 订购单", sqlcon);
myds = new DataSet();
sqlcon.Open();
myda.Fill(myds);
sqlcon.Close();
dataGridView1.DataSource = myds.Tables[0];
} private void button2_Click(object sender, EventArgs e)
{
this.Close();
Application.Exit();
}
}
}

回答2:

public void Keep()
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
//利用流导出Exce
saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
saveFileDialog.FileName = "客户信息";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "另存信息";
saveFileDialog.ShowDialog();
Stream myStream; try
{
myStream = saveFileDialog.OpenFile();
}
catch
{
return;
}
StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
string str = "";
try
{
//写标题
for (int i = 0; i < this.dgvClient.ColumnCount; i++)
{
if (i > 0)
{
str += "\t";
}
str +=this.dgvClient.Columns[i].HeaderText; }
sw.WriteLine(str);
//写内容 for (int j = 1; j < this.dgvClient.Rows.Count; j++)
{
string tempStr = ""; for (int k = 1; k < this.dgvClient.Columns.Count; k++)
{
if (k > 0)
{ tempStr += "\t";
} tempStr += this.dgvClient.Rows[j].Cells[k].Value.ToString(); }
sw.WriteLine(tempStr); }
sw.Close();
myStream.Close(); } catch (Exception ex)
{
MessageBox.Show(ex.ToString());
} finally
{
sw.Close();
myStream.Close();
}
}