这里提供了两种将DataGridView内容导出到Excel文件的方法。
成都创新互联长期为上1000家客户提供的网站建设服务,团队从业经验10年,关注不同地域、不同群体,并针对不同对象提供差异化的产品和服务;打造开放共赢平台,与合作伙伴共同营造健康的互联网生态环境。为嘉峪关企业提供专业的网站设计制作、成都网站制作,嘉峪关网站改版等技术服务。拥有十载丰富建站经验和众多成功案例,为您定制开发。方法1:
/// <summary>
/// 在没有安装Excel的情况下,将DataGridView数据导出到Excel
/// </summary>
private void ExportToExcel()
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "导出到Excel";
saveFileDialog.ShowDialog();
if (saveFileDialog.FileName == "")
{
return;
}
Stream myStream = saveFileDialog.OpenFile();
StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
string str = "";
try
{
for (int i = 0; i < dataGridView1.ColumnCount; i++)
{
if (dataGridView1.Columns[i].Visible == false || dataGridView1.Columns[i].DataPropertyName == "")
{
continue;
}
str += dataGridView1.Columns[i].HeaderText;
str += "\t";
}
sw.WriteLine(str);
for (int j = 0; j < dataGridView1.Rows.Count - 1; j++)
{
string strTemp = "";
for (int k = 0; k < dataGridView1.Columns.Count; k++)
{
if (dataGridView1.Columns[k].Visible == false || dataGridView1.Columns[k].DataPropertyName == "")
{
continue;
}
object obj = dataGridView1.Rows[j].Cells[k].Value;
if (obj != null)
{
strTemp += dataGridView1.Rows[j].Cells[k].Value.ToString();
}
else
{
strTemp = "";
}
strTemp += "\t";
}
sw.WriteLine(strTemp);
}
sw.Close();
myStream.Close();
MessageBox.Show("成功导出到Excel文件:\n" + saveFileDialog.FileName);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
sw.Close();
myStream.Close();
}
}
方法2:
/// <summary>
/// 将DataGrirdView数据导出到Excel
/// 需要引用Microsoft.Office.Interop.Excel.dll模块
/// </summary>
/// <param name="dgv"></param>
/// <param name="bShowExcel"></param>
/// <returns></returns>
private bool DataGridviewShowToExcel(DataGridView dgv, bool bShowExcel)
{
if (dgv.Rows.Count == 0)
{
return false;
}
//建立Excel对象
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
excel.Application.Workbooks.Add(true);
excel.Visible = bShowExcel;
//生成字段名称
int k = 0;
for (int i = 0; i < dgv.ColumnCount; i++)
{
if (dgv.Columns[i].Visible == false || dataGridView1.Columns[i].DataPropertyName == "")
{
k++;
continue;
}
excel.Cells[1, i + 1 - k] = dgv.Columns[i].HeaderText;
}
//填充数据
for (int i = 0; i < dgv.RowCount; i++)
{
k = 0;
for (int j = 0; j < dgv.ColumnCount; j++)
{
if (dgv.Columns[j].Visible == false || dataGridView1.Columns[j].DataPropertyName == "")
{
k++;
continue;
}
excel.Cells[i + 2, j + 1 - k] = dgv[j, i].Value.ToString();
}
}
return true;
}
文章名称:将dataGridView内容导出到Excel文件-创新互联
网页路径:https://www.cdcxhl.com/article32/dccgsc.html
成都网站建设公司_创新互联,为您提供移动网站建设、网站改版、关键词优化、网站制作、微信公众号、域名注册
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联