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

如何用.net把数据库里的数据生成excel文档
比如每个月的工作进度数据,这些数据能用gridview显示,能不能用新建一excel文档,把这些数据写进去呢??

------解决方案--------------------
从数据库读出来后新建一个excel文档
写入就可以了
这个很简单的
C# code

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