private void ExportFromDataGrid(string targetName, System.Web.UI.WebControls.GridView  sourceGrid)
    {
        if (sourceGrid.Rows.Count <= 0)
        {
            return;
        }        int colcount = sourceGrid.Rows[0].Cells.Count;
       int colhcount = sourceGrid.Columns.Count;
         //int colhcount = sourceGrid.Rows[0].Cells.Count;        int rowcount = sourceGrid.Rows.Count;
        Response.AddHeader("Content-Disposition", "attachment;filename=" + targetName);
        Response.ContentEncoding = System.Text.Encoding.GetEncoding("BIG5");
        Response.ContentType = "application/excel";
        //Response.ContentType = "application/vnd.ms-excel";
        Response.Write("半成品入庫\n");
        string temp = "";
        //for (int i = 0; i < colhcount; i++)
        //{
        //    //temp += sourceGrid.Columns[i].HeaderText.ToString() + "\t";
        //}
        temp = "五通碼\t車種代碼\t月份代碼\t廠商代碼\t架高代碼\t顏色代碼\t庫存狀況\t備注";
        temp += "\n";
        Response.Write(temp);
        for (int r=0; r < rowcount; r++)
        {
            string strval = "";
            int c = 2;
          if (SFID) { c += 1; }
        //if (SFIE) { r += 1; }            for (c = c; c < colcount; c++)
            {
                strval += sourceGrid.Rows[r].Cells[c].Text.ToString().Replace("&nbsp;","") + "\t";
            }
            strval += "\n";
            Response.Write(strval);
        }
        Response.Flush();
        Response.Close();
        Response.End();
    }
我是用上面這種方法導出覺得是比較完美的,因為不會連背景和格式都導出,隻導出數字,或字符。
但現在又遇到一個問題,標題單元格怎麼合並呢?比如有五列的話。