日期:2014-05-18 浏览次数:20581 次
protected void ExportOriginalData() { Stream mystream; Connection con = new Connection(); SqlConnection conn; conn = con.Create(); conn.Open(); SqlDataAdapter da = new SqlDataAdapter("select * from data", conn); DataSet ds = new DataSet(); da.Fill(ds, "mytable"); DataTable dt = ds.Tables["mytable"]; if ((mystream = saveFileDialog1.OpenFile()) != null) { System.IO.StreamWriter sw = new StreamWriter(mystream, System.Text.Encoding.Default); for (int i = 0; i < dt.Columns.Count; i++) { sw.Write(dt.Columns[i].ColumnName.ToString() + "\t"); } sw.WriteLine(); for (int i = 0; i < dt.Rows.Count; i++) { for (int j = 0; j < dt.Columns.Count; j++) { sw.Write(dt.Rows[i][j].ToString().Replace("\r\n", "").Replace("\t", "") + "\t"); } sw.WriteLine(); } sw.Close(); mystream.Close(); } ChangeStatus(false); }
------解决方案--------------------
http://www.cnblogs.com/dengxinghong/archive/2008/04/04/1137853.html
------解决方案--------------------
C#,GridView导出到Excel
/// <summary>
/// 导出到Excel
/// </summary>
/// <param name="dgv"></param>
/// <param name="title"></param>
public static void DataGridViewToExcel(DataGridView dgv, string title)
{
if (dgv.DataSource == null || dgv.Columns.Count == 0)
{
return;
}
Excel.Application exc = new Excel.ApplicationClass();
if (exc == null)
{
throw new Exception("Excel无法启动");
}
Workbooks workbooks = exc.Workbooks;
_Workbook workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet);
Sheets sheets = exc.Sheets;
_Worksheet worksheet = (_Worksheet)sheets[1];
if (worksheet == null)
{
throw new Exception("Worksheet error");
}
DataGridViewClipboardCopyMode bakMode = dgv.ClipboardCopyMode;
bool copyCurrentCellText = true;
bool showRowHeader = dgv.RowHeadersVisible;
if (dgv is gvGridView)
{
copyCurrentCellText = ((gvGridView)dgv).CopyCurrentCellText;
((gvGridView)dgv).CopyCurrentCellText = false;
}
dgv.RowHeadersVisible = false;
IDataObject bakClipbordDasta = Clipboard.GetDataObject();
dgv.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText;
IDataObject exportData = dgv.GetClipboardContent();
if (exportData != null)
{
DataObject data = exportData as DataObject;
Clipboard.SetDataObject(data.GetText(TextDataFormat.UnicodeText));
}
if (dgv is gvGridView)
{
((gvGridView)dgv).CopyCurrentCellText = copyCurrentCellText;
}
dgv.RowHeadersVisible = showRowHeader