本文介绍了在这里我从Sql获取数据到Gridview并导出到Excele ..它不工作我不知道Wats错误的这个编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using Satham.DataAccess1;
namespace exptoexl
{
public partial class Form1 : Form
{
DataTable dt = new DataTable();
DBAccess db = new DBAccess();
public Form1()
{
InitializeComponent();
}
private void btnload_Click(object sender, EventArgs e)
{
// DataRow dr = dt.NewRow();
// dt.Rows.Add(dr);
dataGridView1.DataSource = dt;
string sSql = "SELECT * FROM `fxwalkincustomer`";
db.ExecuteNonQuery(sSql);
dt = db.GetDataTable(sSql);
dataGridView1.DataSource = dt;
MessageBox.Show("Loading Complete");
}
private void btnexport_Click(object sender, EventArgs e)
{
load.InitialDirectory = "C:/Windows";
load.Title = "save as ExcelFile";
load.FileName = "";
load.Filter = "Excel Files(2003)|*.xls|Excel Files(2007)|*.xlsx|Excel Workbook|*.xlsx";
if (load.ShowDialog() != DialogResult.Cancel)
{
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
app.Visible = false;
worksheet = workbook.Sheets["Sheet1"];
worksheet = workbook.ActiveSheet;
app.Columns.ColumnWidth = 20;
worksheet.Name = "Exported from dtaaGridView1";
for (int i = 1; i < dataGridView1.Columns.Count + 1; i++)
{
worksheet.Cells[1, i] = dataGridView1.Columns[i - 1].HeaderText;
}
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
worksheet.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
}
}
app.ActiveWorkbook.SaveCopyAs(load.FileName.ToString());
app.ActiveWorkbook.Saved = true;
app.Quit();
}
}
}
}
推荐答案
这篇关于在这里我从Sql获取数据到Gridview并导出到Excele ..它不工作我不知道Wats错误的这个编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!