日期:2014-05-18  浏览次数:20804 次

c# 怎么把dataGridView的数据 用Excel导出!
求一代码.怎么把DataGridview中的数据导入到Excel中.请各位大侠给予指点.小弟初学者忘给予支持谢谢

------解决方案--------------------
private void Export(string FileType, string FileName)
{//導出Excel
Response.Charset = "Big5";
Response.ContentEncoding = System.Text.Encoding.UTF7;
Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());
Response.ContentType = FileType;
this.EnableViewState = false;
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
GridView1.RenderControl(hw);
Response.Write(tw.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{

}
**.aspx页面中要加:EnableEventValidation = "false"
------解决方案--------------------
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using Excel = Microsoft.Office.Interop.Excel;
namespace ConsoleApplication18
{
class Program
{
static void Main(string[] args)
{
ExportDataToExcel("server=(local);uid=sa;pwd=sqlgis;database=master",
"select * from sysobjects",@"c:\testADO.xls","sysobjects");
}

static void ExportDataToExcel(string connectionString,string sql,string fileName,string sheetName)
{
Excel.Application app = new Excel.ApplicationClass();
Excel.Workbook wb = (Excel.WorkbookClass)app.Workbooks.Add(Missing.Value);
Excel.Worksheet ws = wb.Worksheets.Add(Missing.Value, Missing.Value, Missing.Value, Missing.Value) as Excel.Worksheet;
ws.Name = sheetName;
try
{
ADODB.Connection conn = new ADODB.ConnectionClass();
conn.Open("driver={SQL Server};"+connectionString,"","",0);
ADODB.Recordset rs = new ADODB.RecordsetClass();
rs.Open(sql, conn, ADODB.CursorTypeEnum.adOpenStatic, ADODB.LockTypeEnum.adLockReadOnly, 0);
Excel.Range range = ws.get_Range("A2", Missing.Value);
range.CopyFromRecordset(rs, 65535, 65535);
}
catch (Exception ex)
{
string str = ex.Message;
}
finally
{
wb.Saved = true;
wb.SaveCopyAs(fileName);//保存
app.Quit();//关闭进程
}
}
}
}

------解决方案--------------------
用流保存成xls文件:
using System.IO;
/// <summary>

/// 另存新档按钮

/// </summary>

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"; 


saveFileDialog.ShowDialog();


Stream myStream;

myStream = saveFileDialog.OpenFile();

//StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("gb2312"));

StreamWriter sw = new Stre