最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

C# 各種導(dǎo)出的方法總結(jié)

 更新時(shí)間:2017年05月15日 09:58:03   作者:7個(gè)月  
本篇文章主要介紹了C# 各種導(dǎo)出方法的相關(guān)知識(shí),具有很好的參考價(jià)值。下面跟著小編一起來看下吧

第一種:使用 Microsoft.Office.Interop.Excel.dll

首先需要安裝 office 的 excel,然后再找到 Microsoft.Office.Interop.Excel.dll 組件,添加到引用。

public void ExportExcel(DataTable dt)
    {
      if (dt != null)
      {
        Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();

        if (excel == null)
        {
          return;
        }

        //設(shè)置為不可見,操作在后臺(tái)執(zhí)行,為 true 的話會(huì)打開 Excel
        excel.Visible = false;

        //打開時(shí)設(shè)置為全屏顯式
        //excel.DisplayFullScreen = true;

        //初始化工作簿
        Microsoft.Office.Interop.Excel.Workbooks workbooks = excel.Workbooks;

        //新增加一個(gè)工作簿,Add()方法也可以直接傳入?yún)?shù) true
        Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
        //同樣是新增一個(gè)工作簿,但是會(huì)彈出保存對(duì)話框
        //Microsoft.Office.Interop.Excel.Workbook workbook = excel.Application.Workbooks.Add(true);

        //新增加一個(gè) Excel 表(sheet)
        Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];

        //設(shè)置表的名稱
        worksheet.Name = dt.TableName;
        try
        {
          //創(chuàng)建一個(gè)單元格
          Microsoft.Office.Interop.Excel.Range range;

          int rowIndex = 1;    //行的起始下標(biāo)為 1
          int colIndex = 1;    //列的起始下標(biāo)為 1

          //設(shè)置列名
          for (int i = 0; i < dt.Columns.Count; i++)
          {
            //設(shè)置第一行,即列名
            worksheet.Cells[rowIndex, colIndex + i] = dt.Columns[i].ColumnName;

            //獲取第一行的每個(gè)單元格
            range = worksheet.Cells[rowIndex, colIndex + i];

            //設(shè)置單元格的內(nèi)部顏色
            range.Interior.ColorIndex = 33;

            //字體加粗
            range.Font.Bold = true;

            //設(shè)置為黑色
            range.Font.Color = 0;

            //設(shè)置為宋體
            range.Font.Name = "Arial";

            //設(shè)置字體大小
            range.Font.Size = 12;

            //水平居中
            range.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;

            //垂直居中
            range.VerticalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;
          }

          //跳過第一行,第一行寫入了列名
          rowIndex++;

          //寫入數(shù)據(jù)
          for (int i = 0; i < dt.Rows.Count; i++)
          {
            for (int j = 0; j < dt.Columns.Count; j++)
            {
              worksheet.Cells[rowIndex + i, colIndex + j] = dt.Rows[i][j].ToString();
            }
          }

          //設(shè)置所有列寬為自動(dòng)列寬
          //worksheet.Columns.AutoFit();

          //設(shè)置所有單元格列寬為自動(dòng)列寬
          worksheet.Cells.Columns.AutoFit();
          //worksheet.Cells.EntireColumn.AutoFit();

          //是否提示,如果想刪除某個(gè)sheet頁(yè),首先要將此項(xiàng)設(shè)為fasle。
          excel.DisplayAlerts = false;

          //保存寫入的數(shù)據(jù),這里還沒有保存到磁盤
          workbook.Saved = true;

          //設(shè)置導(dǎo)出文件路徑
          string path = HttpContext.Current.Server.MapPath("Export/");

          //設(shè)置新建文件路徑及名稱
          string savePath = path + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + ".xlsx";

          //創(chuàng)建文件
          FileStream file = new FileStream(savePath, FileMode.CreateNew);

          //關(guān)閉釋放流,不然沒辦法寫入數(shù)據(jù)
          file.Close();
          file.Dispose();

          //保存到指定的路徑
          workbook.SaveCopyAs(savePath);

          //還可以加入以下方法輸出到瀏覽器下載
          FileInfo fileInfo = new FileInfo(savePath);
          OutputClient(fileInfo);
        }
        catch(Exception ex)
        {

        }
        finally
        {
          workbook.Close(false, Type.Missing, Type.Missing);
          workbooks.Close();

          //關(guān)閉退出
          excel.Quit();

          //釋放 COM 對(duì)象
          Marshal.ReleaseComObject(worksheet);
          Marshal.ReleaseComObject(workbook);
          Marshal.ReleaseComObject(workbooks);
          Marshal.ReleaseComObject(excel);

          worksheet = null;
          workbook = null;
          workbooks = null;
          excel = null;
          GC.Collect();
        }
      }
    }

public void OutputClient(FileInfo file)
    {
      HttpContext.Current.Response.Buffer = true;

      HttpContext.Current.Response.Clear();
      HttpContext.Current.Response.ClearHeaders();
      HttpContext.Current.Response.ClearContent();

      HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";

      //導(dǎo)出到 .xlsx 格式不能用時(shí),可以試試這個(gè)
      //HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

      HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xlsx", DateTime.Now.ToString("yyyy-MM-dd-HH-mm")));

      HttpContext.Current.Response.Charset = "GB2312";
      HttpContext.Current.Response.ContentEncoding = Encoding.GetEncoding("GB2312");

      HttpContext.Current.Response.AddHeader("Content-Length", file.Length.ToString());

      HttpContext.Current.Response.WriteFile(file.FullName);
      HttpContext.Current.Response.Flush();
      HttpContext.Current.Response.Close();
    }

第一種方法性能實(shí)在是不敢恭維,而且局限性太多。首先必須要安裝 office(如果計(jì)算機(jī)上面沒有的話),而且導(dǎo)出時(shí)需要指定文件保存的路徑。也可以輸出到瀏覽器下載,當(dāng)然前提是已經(jīng)保存寫入數(shù)據(jù)。

第二種:使用 Aspose.Cells.dll

這個(gè) Aspose.Cells 是 Aspose 公司推出的導(dǎo)出 Excel 的控件,不依賴 Office,商業(yè)軟件,收費(fèi)的。

public void ExportExcel(DataTable dt)
    {
      try
      {
        //獲取指定虛擬路徑的物理路徑
        string path = HttpContext.Current.Server.MapPath("DLL/") + "License.lic";

        //讀取 License 文件
        Stream stream = (Stream)File.OpenRead(path);

        //注冊(cè) License
        Aspose.Cells.License li = new Aspose.Cells.License();
        li.SetLicense(stream);

        //創(chuàng)建一個(gè)工作簿
        Aspose.Cells.Workbook workbook = new Aspose.Cells.Workbook();

        //創(chuàng)建一個(gè) sheet 表
        Aspose.Cells.Worksheet worksheet = workbook.Worksheets[0];

        //設(shè)置 sheet 表名稱
        worksheet.Name = dt.TableName;

        Aspose.Cells.Cell cell;

        int rowIndex = 0;  //行的起始下標(biāo)為 0
        int colIndex = 0;  //列的起始下標(biāo)為 0

        //設(shè)置列名
        for (int i = 0; i < dt.Columns.Count; i++)
        {
          //獲取第一行的每個(gè)單元格
          cell = worksheet.Cells[rowIndex, colIndex + i];

          //設(shè)置列名
          cell.PutValue(dt.Columns[i].ColumnName);

          //設(shè)置字體
          cell.Style.Font.Name = "Arial";

          //設(shè)置字體加粗
          cell.Style.Font.IsBold = true;

          //設(shè)置字體大小
          cell.Style.Font.Size = 12;

          //設(shè)置字體顏色
          cell.Style.Font.Color = System.Drawing.Color.Black;

          //設(shè)置背景色
          cell.Style.BackgroundColor = System.Drawing.Color.LightGreen;
        }

        //跳過第一行,第一行寫入了列名
        rowIndex++;

        //寫入數(shù)據(jù)
        for (int i = 0; i < dt.Rows.Count; i++)
        {
          for (int j = 0; j < dt.Columns.Count; j++)
          {
            cell = worksheet.Cells[rowIndex + i, colIndex + j];

            cell.PutValue(dt.Rows[i][j]);
          }
        }

        //自動(dòng)列寬
        worksheet.AutoFitColumns();

        //設(shè)置導(dǎo)出文件路徑
        path = HttpContext.Current.Server.MapPath("Export/");

        //設(shè)置新建文件路徑及名稱
        string savePath = path + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + ".xlsx";

        //創(chuàng)建文件
        FileStream file = new FileStream(savePath, FileMode.CreateNew);

        //關(guān)閉釋放流,不然沒辦法寫入數(shù)據(jù)
        file.Close();
        file.Dispose();

        //保存至指定路徑
        workbook.Save(savePath);

        //或者使用下面的方法,輸出到瀏覽器下載。
        //byte[] bytes = workbook.SaveToStream().ToArray();
        //OutputClient(bytes);

        worksheet = null;
        workbook = null;
      }
      catch(Exception ex)
      {
      }
    }
public void OutputClient(byte[] bytes)
    {
      HttpContext.Current.Response.Buffer = true;

      HttpContext.Current.Response.Clear();
      HttpContext.Current.Response.ClearHeaders();
      HttpContext.Current.Response.ClearContent();

      HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
      HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", DateTime.Now.ToString("yyyy-MM-dd-HH-mm")));

      HttpContext.Current.Response.Charset = "GB2312";
      HttpContext.Current.Response.ContentEncoding = Encoding.GetEncoding("GB2312");

      HttpContext.Current.Response.BinaryWrite(bytes);
      HttpContext.Current.Response.Flush();
      HttpContext.Current.Response.Close();
    }

第二種方法性能還不錯(cuò),而且操作也不復(fù)雜,可以設(shè)置導(dǎo)出時(shí)文件保存的路徑,還可以保存為流輸出到瀏覽器下載。

第三種:Microsoft.Jet.OLEDB

這種方法操作 Excel 類似于操作數(shù)據(jù)庫(kù)。下面先介紹一下連接字符串:

// Excel 2003 版本連接字符串
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:/xxx.xls;Extended Properties='Excel 8.0;HDR=Yes;IMEX=2;'";
// Excel 2007 以上版本連接字符串
string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:/xxx.xlsx;Extended Properties='Excel 12.0;HDR=Yes;IMEX=2;'";

Provider:驅(qū)動(dòng)程序名稱

Data Source:指定 Excel 文件的路徑

Extended Properties:Excel 8.0 針對(duì) Excel 2000 及以上版本;Excel 12.0 針對(duì) Excel 2007 及以上版本。

HDR:Yes 表示第一行包含列名,在計(jì)算行數(shù)時(shí)就不包含第一行。NO 則完全相反。

IMEX:0 寫入模式;1 讀取模式;2 讀寫模式。如果報(bào)錯(cuò)為“不能修改表 sheet1 的設(shè)計(jì)。它在只讀數(shù)據(jù)庫(kù)中”,那就去掉這個(gè),問題解決。

以上就是本文的全部?jī)?nèi)容,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來一定的幫助,同時(shí)也希望多多支持腳本之家!

相關(guān)文章

  • 在C#里面給PPT文檔添加注釋的實(shí)現(xiàn)代碼

    在C#里面給PPT文檔添加注釋的實(shí)現(xiàn)代碼

    平常開會(huì)或者做總結(jié)報(bào)告的時(shí)候我們通常都會(huì)用到PowerPoint演示文稿,我們可以在單個(gè)幻燈片或者全部幻燈片里面添加注釋,這樣觀眾可以從注釋內(nèi)容里面獲取更多的相關(guān)信息,需要的朋友可以參考下
    2017-01-01
  • Unity UGUI的ContentSizeFitter內(nèi)容尺寸適應(yīng)器組件使用示例

    Unity UGUI的ContentSizeFitter內(nèi)容尺寸適應(yīng)器組件使用示例

    這篇文章主要為大家介紹了Unity UGUI的ContentSizeFitter內(nèi)容尺寸適應(yīng)器組件使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-08-08
  • .NET垃圾回收器(GC)原理淺析

    .NET垃圾回收器(GC)原理淺析

    這篇文章主要介紹了.NET垃圾回收器(GC)原理淺析,本文先是講解了一些基礎(chǔ)知識(shí)如托管堆(Managed Heap)、CPU寄存器(CPU Register)、根(Roots)等,然后講解了垃圾回收的基本原理、算法等,需要的朋友可以參考下
    2015-01-01
  • C#分屏控件用法實(shí)例

    C#分屏控件用法實(shí)例

    這篇文章主要介紹了C#分屏控件用法實(shí)例,需要的朋友可以參考下
    2014-08-08
  • C#實(shí)現(xiàn)繪制面形圖表的方法詳解

    C#實(shí)現(xiàn)繪制面形圖表的方法詳解

    這篇文章主要介紹了C#實(shí)現(xiàn)繪制面形圖表的方法,對(duì)于C#初學(xué)者很好的掌握C#圖形繪制有一定的借鑒價(jià)值,需要的朋友可以參考下
    2014-07-07
  • C#中datatable序列化與反序列化實(shí)例分析

    C#中datatable序列化與反序列化實(shí)例分析

    這篇文章主要介紹了C#中datatable序列化與反序列化,是datatable的常用技巧,需要的朋友可以參考下
    2014-09-09
  • C#推送信息到APNs的方法

    C#推送信息到APNs的方法

    這篇文章主要介紹了C#推送信息到APNs的方法,涉及C#推送通知到蘋果APNs的實(shí)現(xiàn)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下
    2015-05-05
  • c# webapi 配置swagger的方法

    c# webapi 配置swagger的方法

    這篇文章主要介紹了c# webapi 配置swagger的方法,文中示例代碼非常詳細(xì),幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下
    2020-07-07
  • 基于WPF實(shí)現(xiàn)ListBox拖動(dòng)子項(xiàng)

    基于WPF實(shí)現(xiàn)ListBox拖動(dòng)子項(xiàng)

    這篇文章主要為大家詳細(xì)介紹了如何基于WPF實(shí)現(xiàn)ListBox拖動(dòng)子項(xiàng)效果,文中的示例代碼講解詳細(xì),具有一定的借鑒價(jià)值,有需要的小伙伴可以參考下
    2024-04-04
  • C#重載運(yùn)算符詳解

    C#重載運(yùn)算符詳解

    這篇文章主要介紹了C#重載運(yùn)算符,是進(jìn)行C#程序設(shè)計(jì)中非常重要的一個(gè)技巧,需要的朋友可以參考下
    2014-08-08

最新評(píng)論

侯马市| 长海县| 望谟县| 延安市| 河间市| 上犹县| 龙川县| 唐河县| 大连市| 绥德县| 定陶县| 扎鲁特旗| 平果县| 老河口市| 留坝县| 泗阳县| 正宁县| 紫云| 恩施市| 白玉县| 绍兴市| 疏附县| 盐城市| 若羌县| 登封市| 兴宁市| 静海县| 方城县| 台北县| 缙云县| 大埔县| 威信县| 彭阳县| 镇康县| 井陉县| 娄烦县| 金湖县| 和林格尔县| 交城县| 乌拉特前旗| 青州市|