using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.SqlClient;
namespace ExportExcel
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnExcel_Click(object sender, EventArgs e)
{
SaveAs();
}
private void SaveAs() //另存新档按钮 导出成Excel
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "Export Excel File To";
DialogResult result = saveFileDialog.ShowDialog();
Stream myStream;
if (result == DialogResult.Cancel)
{
return;
}
else
{
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 (i > 0)
{
str += "\t";
}
str += dataGridView1.Columns[i].HeaderText;
}
sw.WriteLine(str);
//写内容
for (int j = 0; j < dataGridView1.Rows.Count; j++)
{
string tempStr = "";
for (int k = 0; k < dataGridView1.Columns.Count; k++)
{
if (k > 0)
{
tempStr += "\t";
}
tempStr += dataGridView1.Rows[j].Cells[k].Value.ToString();
}
sw.WriteLine(tempStr);
}
sw.Close();
myStream.Close();
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
finally
{
sw.Close();
myStream.Close();
}
}
private void Form1_Load(object sender, EventArgs e)
{
string sql = "select * from [user]";
SqlConnection con = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=Test;Integrated Security=True");
SqlCommand com = new SqlCommand(sql,con);
DataSet ds = new DataSet();
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = com;
sda.Fill(ds);
this.dataGridView1.DataSource = ds.Tables[0];
this.dataGridView1.AllowUserToAddRows = false;//不允许用户添加行,如果设置为true,遍历DataGridView时会把最后一条允许用户添加的行算进去,容易导致空指针异常
con.Close();
}
}
}