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

datatable生成excel和excel插入圖片示例詳解

 更新時間:2014年01月11日 11:47:18   作者:  
excel導出在C#代碼中應用己經(jīng)很廣泛了,下面講了datatable生成excel、復制sheet頁、刪除sheet頁、選中sheet頁、另存excel文件、excel中插入圖片等功能

Excel知識點

一、添加引用和命名空間

添加Microsoft.Office.Interop.Excel引用,它的默認路徑是C:\Program Files\Microsoft Visual Studio 9.0\Visual Studio Tools for Office\PIA\Office12\Microsoft.Office.Interop.Excel.dll
代碼中添加引用using Microsoft.Office.Interop.Excel;

二、Excel類的簡單介紹

此命名空間下關于Excel類的結構分別為:
ApplicationClass - 就是我們的excel應用程序。
Workbook - 就是我們平常見的一個個excel文件,經(jīng)常是使用Workbooks類對其進行操作。
Worksheet - 就是excel文件中的一個個sheet頁。
Worksheet.Cells[row, column] - 就是某行某列的單元格,注意這里的下標row和column都是從1開始的,跟我平常用的數(shù)組或集合的下標有所不同。
知道了上述基本知識后,利用此類來操作excel就清晰了很多。

三、Excel的操作

任何操作Excel的動作首先肯定是用excel應用程序,首先要new一個ApplicationClass 實例,并在最后將此實例釋放。

復制代碼 代碼如下:

ApplicationClass xlsApp = new ApplicationClass(); // 1. 創(chuàng)建Excel應用程序對象的一個實例,相當于我們從開始菜單打開Excel應用程序。
if (xlsApp == null)
{
//對此實例進行驗證,如果為null則表示運行此代碼的機器可能未安裝Excel
}

1. 打開現(xiàn)有的Excel文件

復制代碼 代碼如下:

Workbook workbook = xlsApp.Workbooks.Open(excelFilePath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
Worksheet mySheet = workbook.Sheets[1] as Worksheet; //第一個sheet頁
mySheet.Name = "testsheet"; //這里修改sheet名稱

2.復制sheet頁

復制代碼 代碼如下:

mySheet.Copy(Type.Missing, workbook.Sheets[1]); //復制mySheet成一個新的sheet頁,復制完后的名稱是mySheet頁名稱后加一個(2),這里就是testsheet(2),復制完后,Worksheet的數(shù)量增加一個

注意 這里Copy方法的兩個參數(shù),指是的復制出來新的sheet頁是在指定sheet頁的前面還是后面,上面的例子就是指復制的sheet頁在第一個sheet頁的后面。

3.刪除sheet頁

復制代碼 代碼如下:

xlsApp.DisplayAlerts = false; //如果想刪除某個sheet頁,首先要將此項設為fasle。
(xlsApp.ActiveWorkbook.Sheets[1] as Worksheet).Delete();

4.選中sheet頁

復制代碼 代碼如下:

(xlsApp.ActiveWorkbook.Sheets[1] as Worksheet).Select(Type.Missing); //選中某個sheet頁

5.另存excel文件

復制代碼 代碼如下:

workbook.Saved = true;
workbook.SaveCopyAs(filepath);

6.釋放excel資源

復制代碼 代碼如下:

workbook.Close(true, Type.Missing, Type.Missing);
workbook = null;
xlsApp.Quit();
xlsApp = null;

一般的我們傳入一個DataTable生成Excel代碼

復制代碼 代碼如下:

/// <summary>
///
/// </summary>
/// <param name="dt"></param>
protected void ExportExcel(DataTable dt)
{
    if (dt == null||dt.Rows.Count==0) return;
    Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();

    if (xlApp == null)
    {
        return;
    }
    System.Globalization.CultureInfo CurrentCI = System.Threading.Thread.CurrentThread.CurrentCulture;
    System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
    Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
    Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
    Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];
    Microsoft.Office.Interop.Excel.Range range;
    long totalCount = dt.Rows.Count;
    long rowRead = 0;
    float percent = 0;
    for (int i = 0; i < dt.Columns.Count; i++)
    {
        worksheet.Cells[1, i + 1] = dt.Columns[i].ColumnName;
        range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[1, i + 1];
        range.Interior.ColorIndex = 15;
        range.Font.Bold = true;
    }
    for (int r = 0; r < dt.Rows.Count; r++)
    {
        for (int i = 0; i < dt.Columns.Count; i++)
        {
            worksheet.Cells[r + 2, i + 1] = dt.Rows[r][i].ToString();
        }
        rowRead++;
        percent = ((float)(100 * rowRead)) / totalCount;
    }
    xlApp.Visible = true;
}

如果要在excel中插入圖片,我們需要把代碼加入一行即可,如下所示

復制代碼 代碼如下:

protected void ExportExcel(DataTable dt)
{
    if (dt == null || dt.Rows.Count == 0) return;
    Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();

    if (xlApp == null)
    {
        return;
    }
    System.Globalization.CultureInfo CurrentCI = System.Threading.Thread.CurrentThread.CurrentCulture;
    System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
    Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
    Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
    Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];
    Microsoft.Office.Interop.Excel.Range range;
    long totalCount = dt.Rows.Count;
    long rowRead = 0;
    float percent = 0;
    for (int i = 0; i < dt.Columns.Count; i++)
    {
        worksheet.Cells[1, i + 1] = dt.Columns[i].ColumnName;
        range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[1, i + 1];
        range.Interior.ColorIndex = 15;
    }
    for (int r = 0; r < dt.Rows.Count; r++)
    {
        for (int i = 0; i < dt.Columns.Count; i++)
        {
            try
            {
                worksheet.Cells[r + 2, i + 1] = dt.Rows[r][i].ToString();
            }
            catch
            {
                worksheet.Cells[r + 2, i + 1] = dt.Rows[r][i].ToString().Replace("=", "");
            }
        }
        rowRead++;
        percent = ((float)(100 * rowRead)) / totalCount;
    }

    worksheet.Shapes.AddPicture("C:\\Users\\spring\\Desktop\\1.gif", Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, 100, 200, 200, 300);
    worksheet.Shapes.AddTextEffect(Microsoft.Office.Core.MsoPresetTextEffect.msoTextEffect1, "123456", "Red", 15, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoTrue, 150, 200);
    xlApp.Visible = true;
}

我們調用如下:

復制代碼 代碼如下:

public void GenerateExcel()
{
    DataTable dt = new DataTable();
    dt.Columns.Add("Name", typeof(string));
    dt.Columns.Add("Age", typeof(string));
    DataRow dr = dt.NewRow();
    dr["Name"] = "spring";
    dr["Age"] = "20";
    dt.Rows.Add(dr);
    dt.AcceptChanges();
    ExportExcel(dt);
}

其中如下代碼的作用是

復制代碼 代碼如下:

worksheet.Shapes.AddPicture("C:\\Users\\spring\\Desktop\\1.gif", Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, 100, 200, 200, 300);

在Excel的指定位置加入圖片

復制代碼 代碼如下:

worksheet.Shapes.AddTextEffect(Microsoft.Office.Core.MsoPresetTextEffect.msoTextEffect1, "123456", "Red", 15, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoTrue, 150, 200);
 

在Excel的指定位置加入文本框,和里面的內容.

我們可以這樣來設計一個ExcelBase的基類:

先創(chuàng)建一個ExcelBE.cs:

復制代碼 代碼如下:

public class ExcelBE
 {
     private int _row = 0;
     private int _col = 0;
     private string _text = string.Empty;
     private string _startCell = string.Empty;
     private string _endCell = string.Empty;
     private string _interiorColor = string.Empty;
     private bool _isMerge = false;
     private int _size = 0;
     private string _fontColor = string.Empty;
     private string _format = string.Empty;

     public ExcelBE(int row, int col, string text, string startCell, string endCell, string interiorColor, bool isMerge, int size, string fontColor, string format)
     {
         _row = row;
         _col = col;
         _text = text;
         _startCell = startCell;
         _endCell = endCell;
         _interiorColor = interiorColor;
         _isMerge = isMerge;
         _size = size;
         _fontColor = fontColor;
         _format = format;
     }

     public ExcelBE()
     { }

     public int Row
     {
         get { return _row; }
         set { _row = value; }
     }

     public int Col
     {
         get { return _col; }
         set { _col = value; }
     }

     public string Text
     {
         get { return _text; }
         set { _text = value; }
     }

     public string StartCell
     {
         get { return _startCell; }
         set { _startCell = value; }
     }

     public string EndCell
     {
         get { return _endCell; }
         set { _endCell = value; }
     }

     public string InteriorColor
     {
         get { return _interiorColor; }
         set { _interiorColor = value; }
     }

     public bool IsMerge
     {
         get { return _isMerge; }
         set { _isMerge = value; }
     }

     public int Size
     {
         get { return _size; }
         set { _size = value; }
     }

     public string FontColor
     {
         get { return _fontColor; }
         set { _fontColor = value; }
     }

     public string Formart
     {
         get { return _format; }
         set { _format = value; }
     }

 }

接下來創(chuàng)建ExcelBase.cs:

復制代碼 代碼如下:

public class ExcelBase
{
    private Microsoft.Office.Interop.Excel.Application app = null;
    private Microsoft.Office.Interop.Excel.Workbook workbook = null;
    private Microsoft.Office.Interop.Excel.Worksheet worksheet = null;
    private Microsoft.Office.Interop.Excel.Range workSheet_range = null;

    public ExcelBase()
    {
        createDoc();
    }

    public void createDoc()
    {
        try
        {
            app = new Microsoft.Office.Interop.Excel.Application();
            app.Visible = true;
            workbook = app.Workbooks.Add(1);
            worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets[1];
        }
        catch (Exception e)
        {
            Console.Write("Error");
        }
        finally
        {
        }
    }

    public void InsertData(ExcelBE be)
    {
        worksheet.Cells[be.Row, be.Col] = be.Text;
        workSheet_range = worksheet.get_Range(be.StartCell, be.EndCell);
        workSheet_range.MergeCells = be.IsMerge;
        workSheet_range.Interior.Color = GetColorValue(be.InteriorColor);
        workSheet_range.Borders.Color = System.Drawing.Color.Black.ToArgb();
        workSheet_range.ColumnWidth = be.Size;
        workSheet_range.Font.Color = string.IsNullOrEmpty(be.FontColor) ? System.Drawing.Color.White.ToArgb() : System.Drawing.Color.Black.ToArgb();
        workSheet_range.NumberFormat = be.Formart;
    }

    private int GetColorValue(string interiorColor)
    {
        switch (interiorColor)
        {
            case "YELLOW":
                return System.Drawing.Color.Yellow.ToArgb();
            case "GRAY":
                return System.Drawing.Color.Gray.ToArgb();
            case "GAINSBORO":
                return System.Drawing.Color.Gainsboro.ToArgb();
            case "Turquoise":
                return System.Drawing.Color.Turquoise.ToArgb();
            case "PeachPuff":
                return System.Drawing.Color.PeachPuff.ToArgb();

            default:
                return System.Drawing.Color.White.ToArgb();
        }
    }
}

調用的代碼如下:

復制代碼 代碼如下:

private void btnRun_Click(object sender, EventArgs e)
{
    ExcelBase excel = new ExcelBase();
    //creates the main header
    ExcelBE be = null;
    be = new ExcelBE (5, 2, "Total of Products", "B5", "D5", "YELLOW", true, 10, "n",null);
    excel.InsertData(be);
    //creates subheaders
    be = new ExcelBE (6, 2, "Sold Product", "B6", "B6", "GRAY", true, 10, "",null);
    excel.InsertData(be);
    be=new ExcelBE(6, 3, "", "C6", "C6", "GRAY", true, 10, "",null);
    excel.InsertData(be);
    be=new ExcelBE (6, 4, "Initial Total", "D6", "D6", "GRAY", true, 10, "",null);
    excel.InsertData(be);
    //add Data to cells
    be=new ExcelBE (7, 2, "114287", "B7", "B7",null,false,10,"", "#,##0");
    excel.InsertData(be);
    be=new ExcelBE (7, 3, "", "C7", "C7", null,false,10,"",null);
    excel.InsertData(be);
    be = new ExcelBE(7, 4, "129121", "D7", "D7", null, false, 10, "", "#,##0");
    excel.InsertData(be);
    //add percentage row
    be = new ExcelBE(8, 2, "", "B8", "B8", null, false, 10, "", "");
    excel.InsertData(be);
    be = new ExcelBE(8, 3, "=B7/D7", "C8", "C8", null, false, 10, "", "0.0%");
    excel.InsertData(be);
    be = new ExcelBE(8, 4, "", "D8", "D8", null, false, 10, "", "");
    excel.InsertData(be);
    //add empty divider
    be = new ExcelBE(9, 2, "", "B9", "D9", "GAINSBORO", true, 10, "",null);
    excel.InsertData(be);  

}


相關文章

  • 在Linux上運行C#的方法

    在Linux上運行C#的方法

    這篇文章主要介紹了在Linux上運行C#的方法,實例分析了Linux平臺下Mono軟件包的應用技巧,以及在此基礎之上的C#運行方法,具有一定的參考借鑒價值,需要的朋友可以參考下
    2014-12-12
  • .NET使用C#導入Excel文件數(shù)據(jù)到數(shù)據(jù)庫

    .NET使用C#導入Excel文件數(shù)據(jù)到數(shù)據(jù)庫

    將Excel文件中的數(shù)據(jù)導入到數(shù)據(jù)庫中不僅能夠提升數(shù)據(jù)處理的效率和準確性,還能極大地促進數(shù)據(jù)分析和決策制定的過程,本文將介紹如何在.NET平臺使用C#導入Excel文件數(shù)據(jù)到數(shù)據(jù)庫中,需要的可以參考下
    2024-12-12
  • 基于C#解決庫存扣減及訂單創(chuàng)建時防止并發(fā)死鎖的問題

    基于C#解決庫存扣減及訂單創(chuàng)建時防止并發(fā)死鎖的問題

    這篇文章主要介紹了基于C#解決庫存扣減及訂單創(chuàng)建時防止并發(fā)死鎖的問題,很多開發(fā)人員對于這個問題的排查起來是比較困難的,而生產生的原因多種多樣,很多人認是因為表中的數(shù)據(jù)太多了同時操作的人多人才會產生這種錯誤,下面我們來還原一下死鎖的過程
    2022-05-05
  • C# TextBox數(shù)據(jù)綁定的方法

    C# TextBox數(shù)據(jù)綁定的方法

    這篇文章主要為大家詳細介紹了C# TextBox數(shù)據(jù)綁定的方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-09-09
  • C#自定義Key類型的字典無法序列化的解決方案詳解

    C#自定義Key類型的字典無法序列化的解決方案詳解

    當我們使用System.Text.Json.JsonSerializer對一個字典對象進行序列化的時候,默認情況下字典的Key不能是一個自定義的類型,本文整理了幾種解決方案,希望對大家有所幫助
    2024-03-03
  • WPF+SkiaSharp實現(xiàn)自繪拖曳小球

    WPF+SkiaSharp實現(xiàn)自繪拖曳小球

    WPF的拖曳效果,基本配置一下,就可以了,但是自繪的話,就得自己控制。本文將利用WPF+SkiaSharp實現(xiàn)自繪拖曳小球,感興趣的可以動手嘗試一下
    2022-07-07
  • 詳解C#如何監(jiān)控選定文件夾中文件的變動情況

    詳解C#如何監(jiān)控選定文件夾中文件的變動情況

    這篇文章主要為大家詳細介紹了C#如何監(jiān)控選定文件夾中文件的變動情況,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下
    2023-12-12
  • C# PropertyGrid使用案例詳解

    C# PropertyGrid使用案例詳解

    這篇文章主要介紹了C# PropertyGrid使用案例詳解,本篇文章通過簡要的案例,講解了該項技術的了解與使用,以下就是詳細內容,需要的朋友可以參考下
    2021-08-08
  • C#類中方法的執(zhí)行順序是什么

    C#類中方法的執(zhí)行順序是什么

    有些中級開發(fā)小伙伴還是搞不太明白在繼承父類以及不同場景實例化的情況下,父類和子類的各種方法的執(zhí)行順序到底是什么,本文就來介紹一下
    2021-05-05
  • c# 自定義值類型一定不要忘了重寫Equals,否則性能和空間雙雙堪憂

    c# 自定義值類型一定不要忘了重寫Equals,否則性能和空間雙雙堪憂

    這篇文章主要介紹了c# 自定義值類型一定不要忘了重寫Equals,幫助大家提高c# 程序的性能,感興趣的朋友可以了解下
    2020-08-08

最新評論

登封市| 林州市| 思南县| 东乡族自治县| 都江堰市| 江都市| 清新县| 乌鲁木齐县| 崇阳县| 米泉市| 定州市| 涪陵区| 贵德县| 察隅县| 江孜县| 德庆县| 玉溪市| 水富县| 锦屏县| 通城县| 辽阳县| 福州市| 高碑店市| 连城县| 突泉县| 益阳市| 鄂伦春自治旗| 会同县| 康保县| 清丰县| 轮台县| 慈利县| 威信县| 汝州市| 永川市| 台南市| 龙岩市| 通山县| 英山县| 新宾| 甘南县|