有关于c#操作excel的问题 请各位大虾指教

来源:互联网 发布:mac梦想小镇 存档 编辑:程序博客网 时间:2024/04/20 13:23

我用c#写了个程序是将DataGrid中的数据写入excel的
写入成功.但是现在我想在写入的excel中加一行标题
也就是如何用程序在excel中设置显示格式(合并单元格,设置字体)

public void CM_WriteDSToExcel( string dtime ) {
            string strFile = "";
            string path = "";
            OleDbDataAdapter adapter = new OleDbDataAdapter( "SELECT Company, Software, [Key], [Percent], [Date Time] FROM [Key] WHERE ([Date Time] = '" + dtime + "')", conn );
            DataSet ds = new DataSet();

            adapter.Fill( ds );

            DataTable dt = ds.Tables[0];

            //文件信息设置
            strFile = strFile + "Key   ";
            strFile = strFile + DateTime.Now.ToString( "yyyy-MM-dd hh-mm-ss" );
            strFile = strFile + ".xls";
            path = Application.StartupPath + "//" + strFile;

            System.IO.FileStream fs = new FileStream( path, System.IO.FileMode.Create, System.IO.FileAccess.Write );
            StreamWriter sw = new StreamWriter( fs, new System.Text.UnicodeEncoding() );
            //画表头
            for ( int i = 0; i < dt.Columns.Count; i++ ) {
                sw.Write( dt.Columns[i].ColumnName );
                sw.Write( "/t" );
            }
            sw.WriteLine( "" );
            //画表体
            for ( int i = 0; i < dt.Rows.Count; i++ ) {
                sw.Write( dt.Rows[i]["Company"].ToString() );
                sw.Write( "/t" );
                sw.Write( dt.Rows[i]["Software"].ToString() );
                sw.Write( "/t" );
                sw.Write( dt.Rows[i]["Key"].ToString() );
                sw.Write( "/t" );
                sw.Write( dt.Rows[i]["Percent"].ToString() );
                sw.Write( "/t" );
                sw.Write( dt.Rows[i]["Date Time"].ToString() );
                sw.Write( "/t" );
                sw.WriteLine( "" );
            }
            sw.Flush();
            sw.Close();
        }

原创粉丝点击