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 Microsoft.Office.Interop.Excel;
namespace DataGrid_Excel
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void ExportToExcel(DataGridView dataGridView)
{
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
excel.Visible = true;
Microsoft.Office.Interop.Excel.Workbook workbook = excel.Workbooks.Add(System.Reflection.Missing.Value);
Microsoft.Office.Interop.Excel.Worksheet sheet1 = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets[1];
for (int i = 0; i < dataGridView.Columns.Count; i++)
{
sheet1.Cells[1, i + 1] = dataGridView.Columns[i].HeaderText;
}
for (int i = 0; i < dataGridView.Rows.Count; i++)
{
for (int j = 0; j < dataGridView.Columns.Count; j++)
{
sheet1.Cells[i + 2, j + 1] = dataGridView.Rows[i].Cells[j].Value.ToString();
}
}
//workbook.SaveAs(“D:\\ornek.xlsx”, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing, true, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Microsoft.Office.Interop.Excel.XlSaveConflictResolution.xlUserResolution, true, Type.Missing, Type.Missing);
//workbook.Close();
//excel.Quit();
}
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.ColumnCount = 3;
dataGridView1.Columns[0].Name = “Ad”;
dataGridView1.Columns[1].Name = “Soyad”;
dataGridView1.Columns[2].Name = “Telefon”;
dataGridView1.Rows.Add();
dataGridView1.Rows[0].Cells[0].Value = “Yazılım”;
dataGridView1.Rows[0].Cells[1].Value = “Kodlama”;
dataGridView1.Rows[0].Cells[2].Value = “23165135”;
dataGridView1.Rows[1].Cells[0].Value = “Tasarım”;
dataGridView1.Rows[1].Cells[1].Value = “Kodlama”;
dataGridView1.Rows[1].Cells[2].Value = “75251212”;
}
private void button1_Click(object sender, EventArgs e)
{
ExportToExcel(dataGridView1);
}
}
}
Source link