WEB开发网
开发学院数据库MSSQL Server DataSet导出到Excel比较完整的解决方案(二)--服... 阅读

DataSet导出到Excel比较完整的解决方案(二)--服务器端生成文件(downmoon) (下)

 2009-01-16 10:19:11 来源:WEB开发网   
核心提示: 思路:通过读出Excel模板文件到DataTale,再把数据填充到DataTable,文件另存下就OK了!调用代码如下:DataSetToLocalExcelpublic static string path = @"TempExcelSTemp.xls";public

思路:通过读出Excel模板文件到DataTale,再把数据填充到DataTable,文件另存下就OK了!

调用代码如下:

DataSetToLocalExcel

public static string path = @"TempExcelSTemp.xls";
    public static string path2 = "TestUser.xls";
    public static string PreFilePath = @"C:Excel";
    public static void DataSetToLocalExcel(DataSet ds, string srcPath, string outputPath, bool deleteOldFile)
    {
      if (ds == null || ds.Tables[0] == null && ds.Tables[0].Rows.Count == 0) { return; }
      if (deleteOldFile)
      {
        if (System.IO.File.Exists(outputPath)) { System.IO.File.Delete(outputPath); }
      }
      System.IO.File.Copy(srcPath, outputPath, true);
      ExcelReader exr = new ExcelReader();
      exr.ExcelFilename = outputPath;
      exr.Headers = true;
      exr.MixedData = true;
      exr.KeepConnectionOpen = true;
      string[] sheetnames = exr.GetExcelSheetNames();
      exr.SheetName = sheetnames[0];
      DataTable dt = exr.GetTable();
      if (dt == null) return;
      exr.SetPrimaryKey(0);
      //dt.PrimaryKey = new DataColumn[] { dt.Columns["编号"] };
      DataTable dt2 = ds.Tables[0].Copy();
      dt.Rows.Clear();
      for (int i = 0; i < dt2.Rows.Count; i++)
      { // Copy the values to the object array
        DataRow dr = dt.NewRow();
        for (int col = 0; col < dt.Columns.Count; col++)
        {
          dr[col] = dt2.Rows[i][col];
        }
        dt.Rows.Add(dr);
      }
      exr.SetTable(dt);
      WriteFile#region WriteFile
      #endregion
      exr.Close();
      exr.Dispose();
      exr = null;
    }
    private DataSet Get_AllPrices()
    {
      try
      {
        // Get the employee details
        string strSql = "SELECT [CustomID] as 编号,[C_Name] as 品名,0 as 最高价格,0 as 最低价格,0 as 平均价格,'元/公斤' as 计量单位,'' as 备注 FROM [PriceCategory] WHERE ( 1=1 AND ([Puser] = 'tuser') )";
        SqlConnection objConn = new SqlConnection(@"Data Source=AP6;Initial Catalog=testdb2009 ;Persist Security Info=True;User ID=sa;Password=sa");
        SqlDataAdapter daEmp = new SqlDataAdapter(strSql, objConn);
        daEmp.Fill(dsPrice, "price");
        return dsPrice;
      }
      catch (Exception Ex)
      {
        throw Ex;
      }
    }
    DataSet dsPrice = new DataSet();
    protected void btnGetData_Click(object sender, EventArgs e)
    {
      DataSetToLocalExcel(Get_AllPrices(), PreFilePath + path, PreFilePath + path2, true);
    }

Tags:DataSet 导出 Excel

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接