C#写数据到Excel

private void ImportToExcel(string strFileName, DataSet ds)
    {
        Stream myStream = System.IO.File.Create(strFileName);
        StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("gb2312"));
        string str = "";
        try
        {
            //写标题
            for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
            {
                if (i > 0)
                    str += "\t";
                str += ds.Tables[0].Columns[i].ColumnName;
            }
            sw.WriteLine(str);

            for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
            {
                string strTmp = "";
                for (int j = 0; j < ds.Tables[0].Rows.Count; j++)
                {
                    if (j > 0)
                        strTmp += "\t";
                    strTmp += ds.Tables[0].Rows[i][j].ToString();
                }
                sw.WriteLine(strTmp);
            }
            sw.Close();
            myStream.Close();
        }
        catch (Exception ex)
        { }
        finally
        {
            sw.Close();
            myStream.Close();
        }

    }

posted @ 2009-07-27 10:44  马建康  阅读(341)  评论(0编辑  收藏  举报