C#如何表格型數據導出到Excel?


代碼如下:

         int intDataCount = myData.Tables[0].Rows.Count;


       Microsoft.Office.Interop.Excel.Application app = null; Microsoft.Office.Interop.Excel.Workbook workbook = null; Microsoft.Office.Interop.Excel.Worksheet sheet = null;
object missing = System.Reflection.Missing.Value; //     表示 System.Reflection.Missing 類的唯一實例。 string strPath = string.Empty; string strFileName = string.Empty; try { app = new Microsoft.Office.Interop.Excel.Application(); app.Visible = false; // 不顯示,僅后台生成 workbook = app.Workbooks.Add(true); // 如果打開已存在文件,這里用Open,保存使用Save // 添加sheet的方法 workbook.Worksheets.Add(missing, missing, missing, missing); // 修改sheet名的方法,注意sheet的下標從1開始 sheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1]; sheet.Name = "new sheet name"; //想要將sheet的名稱改為Sheet1,則需改 // 添加sheet的方法 // 注銷 workbook.Worksheets.Add(missing, missing, missing, missing); // 中間不變 //sheet.Name = "Sheet1"; //添加標題 app.Cells[1, 1] = strTitle; app.Cells[2, 1] = "項目名稱:" + myData.Tables[0].Rows[0][“columnName”].ToString(); //合並單元格 sheet.get_Range(sheet.Cells[1, 1], sheet.Cells[1, 6]).MergeCells = true; sheet.get_Range(sheet.Cells[2, 1], sheet.Cells[2, 6]).MergeCells = true; //居中對齊 sheet.get_Range(sheet.Cells[1, 1], sheet.Cells[1, 6]).HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter; //設置字體 sheet.get_Range(sheet.Cells[1, 1], sheet.Cells[1, 6]).Font.Size = 13; sheet.get_Range(sheet.Cells[2, 1], sheet.Cells[2, 6]).HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft; // 設置字體和大小 //range = sheet.get_Range(sheet.Cells[1, 1], sheet.Cells[rowCount, columnCount]); //range.Font.Name = “Arial”; //range.Font.Size = 10; // 設置單元格的wrap text屬性 sheet.get_Range(sheet.Cells[3, 1], sheet.Cells[intDataCount + 2, 6]).WrapText = true; // 設置單元格的數據格式為文本格式 sheet.get_Range(sheet.Cells[3, 1], sheet.Cells[intDataCount + 2, 6]).NumberFormat = "@"; //設置自動調整列寬 sheet.get_Range(sheet.Cells[3, 1], sheet.Cells[intDataCount + 2, 6]).EntireColumn.AutoFit();
          //sheet.Range[sheet.Cells[1, 1], sheet.Cells[intDataCount + 1, 13]].EntireColumn.ColumnWidth = 20;

          sheet.Range[sheet.Cells[1, 1], sheet.Cells[intDataCount + 1, 13]].WrapText = false;
          sheet.Range[sheet.Cells[1, 1], sheet.Cells[intDataCount + 1, 13]].NumberFormat = "@";
          sheet.Range[sheet.Cells[1, 1], sheet.Cells[intDataCount + 1, 13]].EntireRow.AutoFit();
          sheet.Range[sheet.Cells[1, 1], sheet.Cells[intDataCount + 1, 13]].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;




Microsoft.Office.Interop.Excel.Range range; Array arr
= Array.CreateInstance(typeof(object), intDataCount + 2, 6); // 不斷的調用下面的的函數填充array中的內容 // 行,列均從0開始 arr.SetValue("列名1", 0, 0); arr.SetValue("列名2", 0, 1); arr.SetValue("列名3", 0, 2); arr.SetValue("列名4", 0, 3); arr.SetValue("列名5", 0, 4); arr.SetValue("列名6", 0, 5); int i = 1; foreach (DataRow row in myData.Tables[0].Rows) { arr.SetValue(row["columnName1"], i, 0); arr.SetValue(row["columnName2"], i, 1); arr.SetValue(row["columnName3"], i, 2); arr.SetValue(row["columnName4"], i, 3); arr.SetValue(row["columnName5"], i, 4); arr.SetValue(row["columnName6"], i, 5); i++; } // 設置array數據,注意選擇的行數和列數要與array行數和列數對應 //sheet.get_Range(sheet.Cells[3, 1], sheet.Cells[intDataCount + 2, 6]).Value2 = arr;          sheet.Range[sheet.Cells[1, 1], sheet.Cells[intDataCount + 1, 13]].Value2 = arr; // 這里給sheet填充內容部分略 // 如果文件已經存在又不想讓“是否替換”的提示窗體顯示出來,需要先調用File.Delete來刪除文件 strFileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx"; strPath = Server.MapPath("~/upload"); workbook.SaveAs(strPath + "\\" + strFileName, missing, missing, missing, missing, missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing, missing);

          HylExcel.NavigateUrl = string.Format(@"{0}/{1}/{2}", PageBase.UrlBase, PageBase.UploadDir, strFileName);
          HylExcel.Text = string.Format("<span style='color:red;font-weight:bold;'>點這里下載Excel文件{0}</span>", strFileName);



                workbook.Close(false, missing, missing);
                app.Quit();
                workbook = null;
                app = null;
                GC.Collect();

                //FileInfo fi = new FileInfo(strPath + "\\" + strFileName);//excelFile為文件在服務器上的地址 
                //HttpResponse contextResponse = HttpContext.Current.Response;
                //contextResponse.Clear();
               // contextResponse.Buffer = true;
               //contextResponse.Charset = "GB2312"; //設置了類型為中文防止亂碼的出現 
               // contextResponse.AppendHeader("Content-Disposition", String.Format("attachment;filename={0}", fi.Name)); //定義輸出文件和文件名 
                ///contextResponse.AppendHeader("Content-Length", fi.Length.ToString());
               //contextResponse.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
                //contextResponse.ContentType = "application/ms-excel";//設置輸出文件類型為excel文件。 

                //contextResponse.WriteFile(fi.FullName);
               // contextResponse.Flush();
                //fi.Delete();
            }
            catch (Exception ex)
            {
                if (app != null)
                {
                    app.Quit();
                    app = null;
                    GC.Collect();
                }
            }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM