How to download DataTable

Posted by b0ksah on Tue, 26 Nov 2019 21:31:19 +0100

There are many ways to download datatable from the server to the local. Here are three ways.

Mode 1: transfer datatable to txt for download.

Steps:

1. Download datatable content to server txt

2. Download the server's txt to the local

3. Delete the txt on the server

Mode 2: the datatable is bound to the control GridView and then downloaded

Steps:

1. Turn off the control paging function and bind data to the control

2. Download control content to local

3. Open the control paging function and rebind the data

Mode 3: transfer datatable to Excel for download

Steps:

1. Download the datatable content to the server Excel

2. Download Excel from server to local

3. Delete Excel on the server

If you have other good ways, you may as well share them. It's better to have source code, hahaha~~~~

//datatable Turn to txt 
public void DataTableToTxt(string filePath,DataTable ds) {
            FileStream fs = new FileStream(filePath, FileMode.Create);
            StreamWriter sw = new StreamWriter(fs);
            //Start writing
            for (int j=0; j < ds.Columns.Count; j++) {
                sw.Write(ds.Columns[j].ColumnName);
                sw.Write("\t");
            }
            sw.Write("\r\n");
                for (int i = 0; i < ds.Rows.Count; i++)
                {
                    for (int j = 0; j < ds.Columns.Count; j++)
                    {
                        sw.Write(ds.Rows[i][j].ToString() == "&nbsp;" ? "" : ds.Rows[i][j].ToString());
                        sw.Write("\t");
                    }
                    sw.Write("\r\n");
                }
            //Clear buffer
            sw.Flush();
            //Closed flow
            sw.Close();
            fs.Close();
        }
//Download control content
public void GridviewToExcel(Control control, string FileType, string FileName)
        {
            HttpContext.Current.Response.Charset = "GB2312";//Set the type to Chinese to prevent the occurrence of garbled code 
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");//Attention code
            HttpContext.Current.Response.AppendHeader("Content-Disposition",
                 "attachment;filename=" + HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8).ToString());//take http Header added to output stream
            HttpContext.Current.Response.ContentType = FileType;//image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword 

            control.Page.EnableViewState = false;//The server only responds once
            StringWriter tw = new StringWriter();//Implement writing information to string(The following information will be written here)
            HtmlTextWriter hw = new HtmlTextWriter(tw);//Used to write markup characters and text to ASP.NET Server control output stream
            control.RenderControl(hw);//Output the contents of the server control to the provided HtmlTextWriter In object
       

            HttpContext.Current.Response.Write("<html><head><meta http-equiv=Content-Type content=\"text/html; charset=gb2312\">");
            HttpContext.Current.Response.Write(tw.ToString());
            HttpContext.Current.Response.Write("</body></html>");
            HttpContext.Current.Response.End();
        }
//call
GridviewToExcel(grd, "application/vnd.ms-excel.numberformat:@", "xx.xls");
//datatable turn excel
public void DataTabletoExcel(System.Data.DataTable tmpDataTable, string strFileName)
        {
            if (tmpDataTable == null)

                return;
            int rowNum = tmpDataTable.Rows.Count;
            int columnNum = tmpDataTable.Columns.Count;
            int rowIndex = 1;
            int columnIndex = 0;
            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
            xlApp.DefaultFilePath = "";
            xlApp.DisplayAlerts = true;
            xlApp.SheetsInNewWorkbook = 1;
            Microsoft.Office.Interop.Excel.Workbook xlBook = xlApp.Workbooks.Add(true);
            Microsoft.Office.Interop.Excel.Worksheet xlSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlBook.ActiveSheet;
            //take DataTable Column name import for Excel Table 1 row
            foreach (DataColumn dc in tmpDataTable.Columns)
            {
                columnIndex++;
                xlApp.Cells[rowIndex, columnIndex] = dc.ColumnName;

            }

            //take DataTable Data import in Excel in
            xlSheet.Range[xlSheet.Cells[1, 1], xlSheet.Cells[rowNum + 1, columnNum+1]].NumberFormatLocal = "@";//Format as text
            for (int i = 0; i < rowNum; i++)
            {              
                rowIndex++;
                columnIndex = 0;
                for (int j = 0; j < columnNum; j++)
                {
                    columnIndex++;
                    xlApp.Cells[rowIndex, columnIndex] = tmpDataTable.Rows[i][j].ToString();

                }

            }    
            //xlBook.SaveCopyAs(HttpUtility.UrlDecode(strFileName, System.Text.Encoding.UTF8));
            xlBook.SaveCopyAs(strFileName);
        }
DataTabletoExcel(ds, Server.MapPath("") + "\\xx.xlsx");
//File download parameter file name file path 
public void DownFileToLocal(string FileName,string FilePath) {
            FileInfo fileInfo = new FileInfo(FilePath);
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.ClearContent();
            HttpContext.Current.Response.ClearHeaders();
            HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName);
            HttpContext.Current.Response.AddHeader("Content-Length", fileInfo.Length.ToString());
            HttpContext.Current.Response.AddHeader("Content-Transfer-Encoding", "binary");
            HttpContext.Current.Response.ContentType = "application/octet-stream";
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
            HttpContext.Current.Response.WriteFile(fileInfo.FullName);
            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.End();
        }

Topics: C# Excel encoding