C#実装データGridViewのデータをExcelにインポート
1.開発環境のメニューから「プロジェクト」|「参照の追加」オプションを選択
2.comタブを選択し、Microsoft Excel 9を選択します.0 Object Libraryの名前を作成し、「OK」ボタンをクリックして追加に成功しました.
3.詳細コードは次のとおりです.
2.comタブを選択し、Microsoft Excel 9を選択します.0 Object Libraryの名前を作成し、「OK」ボタンをクリックして追加に成功しました.
3.詳細コードは次のとおりです.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.Sql;
using System.Data.SqlClient;
namespace excelform
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
/// <summary>
/// DataGridView Excel
/// </summary>
/// <param name="gridView">DataGridView </param>
/// <param name="isShowExcle"> Excel </param>
/// <returns></returns>
public bool ExportDataGridview(DataGridView gridView, bool isShowExcle)
{
if (gridView.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 < gridView.ColumnCount; i++)
{
excel.Cells[1, i + 1] = gridView.Columns[i].HeaderText;
}
//
for (int i = 0; i < gridView.RowCount - 1; i++) //
{
for (int j = 0; j < gridView.ColumnCount; j++) //
{
if (gridView[j, i].ValueType == typeof(string)) // DataGirdView
{
excel.Cells[i + 2, j + 1] = "'" + gridView[j, i].Value.ToString();
}
else
{
excel.Cells[i + 2, j + 1] = gridView[j, i].Value.ToString();
}
}
}
return true;
}
private void button1_Click(object sender, EventArgs e)
{
this.ExportDataGridview(dataGridView1, true);
}
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Server=.;uid=sa;pwd=123;DataBase=accp;");
SqlDataAdapter dap = new SqlDataAdapter("select * from userInfo", con);
DataSet ds = new DataSet();
dap.Fill(ds);
dataGridView1.DataSource = ds.Tables[0].DefaultView;
}
}
}