• asp.net将数据导出为excel有什么好的方法

    [c#]
    post by bgaidu / 2008-10-23 8:19 Thursday
    1、先将网页

    C# code
    private string GetweatherXML()
              {
                   string body = "";
                   System.Net.WebRequest request = System.Net.WebRequest.Create(地址);//创建对weatherURL请求
                   request.Credentials = System.Net.CredentialCache.DefaultCredentials;//安全设置
                   System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();//得到响应
                   if (response.StatusDescription.ToUpper() == "OK")
                   {
                        System.IO.Stream weatherStream = response.GetResponseStream();
                        System.IO.StreamReader read = new System.IO.StreamReader(weatherStream);
                        body = read.ReadToEnd();
                        read.Close();
                        weatherStream.Close();
                   }
                   else
                   {
                        body = string.Empty;
                   }
                   response.Close();
                   return body;
              }



    2、循环读取内容存入数组

    C# code
    private void AssayXML()  
              {
                   XmlReader ObjXml = XmlReader.Create(new System.IO.StringReader(weatherXML));
                   ObjXml.MoveToContent();
                   while (ObjXml.Read())
                   {
    Read//参考网上的方法
                   }
              }



    3、导出到EXCEL

    C# code
    private void FileCrear(string[] swtreaStr)//导出Excel
            {
                SaveFileDialog saveFileDialog = new SaveFileDialog();
                saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
                saveFileDialog.FilterIndex = 0;
                saveFileDialog.RestoreDirectory = true;
                saveFileDialog.Title = "导出Excel文件到";
                saveFileDialog.ShowDialog();
                if (saveFileDialog.FileName != "")
                {
                    try
                    {
                        File.WriteAllLines(saveFileDialog.FileName, swtreaStr, System.Text.Encoding.GetEncoding("gb2312"));
                        Process.Start(saveFileDialog.FileName);
                    }
                    catch
                    {
                        MessageBox.Show("导出失败!");
                        return;
                    }
                    finally
                    {
                        saveFileDialog.Dispose();
                    }
                }
            }
    ------------------------------------------------------------------------------------
    1.建立一个excel文件。
    2.把这个excel文件当成一个数据库连接他
    3.用sql语句生成表
    4.逐条插入数据,关闭连接。
    我的就是这样做的
    -------------------------------------------------------------------------------------------
    C# code

    long totalCount = dt.Rows.Count;   //dt的行数,一会循环要用
    //FileName为路径(注意名字要和表的名字一样,比如在次方法中应为excel,其实这3个参数应该全用变量代替的,呵呵,自己写吧,我不改了)
            string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + FileName+ ";Extended     roperties=Excel 8.0;";
            OleDbConnection objConn = new OleDbConnection(connString);  
            OleDbCommand objCmd = new OleDbCommand();
            objCmd.Connection = objConn;
            objConn.Open();
            //创建表的结构
            objCmd.CommandText = "CREATE TABLE excel(ID int ,字段 varchar)";
            objCmd.ExecuteNonQuery();
            //插入表
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                objCmd.CommandText = "INSERT INTO excel(ID,字段) values"
                    + "('" + dt.Rows[0].ToString() + "','" + dt.Rows[1].ToString() + "')";
                objCmd.ExecuteNonQuery();
            }
            objConn.Close();



    你要的答案!
    ----------------------------------------------------------------
    4. dataset导出到excel
    4.1 写数据
      object missing = System.Reflection.Missing.Value;
                Microsoft.Office.Interop.Excel.ApplicationClass appc = new Microsoft.Office.Interop.Excel.ApplicationClass();//lauch excel
                Microsoft.Office.Interop.Excel.Workbook wb = appc.Application.Workbooks.Add(true);//add new workbook            Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets.get_Item(1);//get first worksheet
                Microsoft.Office.Interop.Excel.Range range = ws.get_Range("A1", "C1");//get range from A1 to C1
      string[] arrValue={"1","2","3"};
                range.Value2 = arrValue;//set value
      .
    或者
    public bool SaveFP2toExcel(string Path)
        {
        try
        {
        string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +"Data Source="+ Path +";"+"Extended Properties=Excel 8.0;";
        OleDbConnection conn = new OleDbConnection(strConn);
        conn.Open();  
        System.Data.OleDb.OleDbCommand cmd=new OleDbCommand ();
        cmd.Connection =conn;
        //cmd.CommandText ="UPDATE [sheet1$] SET 姓名='2005-01-01' WHERE 工号='日期'";
        //cmd.ExecuteNonQuery ();
        for(int i=0;i       {
          if(fp2.Sheets [0].Cells[i,0].Text!="")
          {
          cmd.CommandText ="INSERT INTO [sheet1$] (工号,姓名,部门,职务,日期,时间) VALUES('"+fp2.Sheets [0].Cells[i,0].Text+ "','"+
            fp2.Sheets [0].Cells[i,1].Text+"','"+fp2.Sheets [0].Cells[i,2].Text+"','"+fp2.Sheets [0].Cells[i,3].Text+
            "','"+fp2.Sheets [0].Cells[i,4].Text+"','"+fp2.Sheets [0].Cells[i,5].Text+"')";
          cmd.ExecuteNonQuery ();
          }
        }
        conn.Close ();
        return true;
        }
        catch(System.Data.OleDb.OleDbException ex)
        {
        System.Diagnostics.Debug.WriteLine ("写入Excel发生错误:"+ex.Message );
        }
        return false;
      }

    4.2 格式化
    设置字体颜色
    range.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.White);//white color
    设置背景色
    range.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.MidnightBlue);//set backgroud color
    ------------------------------------------------------------------------
    C#操作excel
    1. 引用的com组件:Microsoft.Office.Interop.Excel.dll,一般安装完office就有这个文件。(office 2003下载这个dll:点击下载)。
    2. 新建一个C#项目,添加前面的dll到引用里面来
    3. 读取excel数据到dataset
    方法一
    private void OpenExcel(string strFileName)
              {
                object missing = System.Reflection.Missing.Value;
                Microsoft.Office.Interop.Excel.ApplicationClass appc = new Microsoft.Office.Interop.Excel.ApplicationClass();//lauch excel application
                if (appc == null)
                  {
                    MessageBox.Show("can't access excel");
                }
                else
                  {
                    // Microsoft.Office.Interop.Excel.Workbook wb = appc.Application.Workbooks.Add(true);
                    //open excel file
                    Microsoft.Office.Interop.Excel.Workbook wb = appc.Application.Workbooks.Open(strFileName, missing, false, missing, missing, missing, missing, missing, missing, true, missing, missing, missing, missing, missing);
                    //get first worksheet
                    Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets.get_Item(1);
                    //get range from A1 to A3                Microsoft.Office.Interop.Excel.Range rng = ws.Cells.get_Range("A1", "A3");                
                    object[,] arrValue = (object[,])rng.Value2;//get range's value
                    string strValue = "";
                    for (int i = 1; i <= arrValue.GetLength(0); i++)
                      {
                        strValue +="Cell"+i+":"+ arrValue[i, 1].ToString()+System.Environment.NewLine;
                    }
                    MessageBox.Show(strValue.ToString());//show value
                }
                appc.Quit();
                appc = null;
                
            }

    方法二
      public DataSet ExcelToDS(string Path)
        {
        string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +"Data Source="+ Path +";"+"Extended Properties=Excel 8.0;";
        OleDbConnection conn = new OleDbConnection(strConn);
        conn.Open();  
        string strExcel = "";  
        OleDbDataAdapter myCommand = null;
        DataSet ds = null;
        strExcel="select * from [sheet1$]";
        myCommand = new OleDbDataAdapter(strExcel, strConn);
        ds = new DataSet();
        myCommand.Fill(ds,"table1");  
        return ds;
      }

    ------------------------------------------------------------------
    
    您对本文的评分:
    当前平均分: 0.0(0 次打分)

    引用地址:

    发表评论: