datatable生成excel和excel插入圖片示例詳解
Excel知識(shí)點(diǎn)
一、添加引用和命名空間
添加Microsoft.Office.Interop.Excel引用,它的默認(rèn)路徑是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類(lèi)的簡(jiǎn)單介紹
此命名空間下關(guān)于Excel類(lèi)的結(jié)構(gòu)分別為:
ApplicationClass - 就是我們的excel應(yīng)用程序。
Workbook - 就是我們平常見(jiàn)的一個(gè)個(gè)excel文件,經(jīng)常是使用Workbooks類(lèi)對(duì)其進(jìn)行操作。
Worksheet - 就是excel文件中的一個(gè)個(gè)sheet頁(yè)。
Worksheet.Cells[row, column] - 就是某行某列的單元格,注意這里的下標(biāo)row和column都是從1開(kāi)始的,跟我平常用的數(shù)組或集合的下標(biāo)有所不同。
知道了上述基本知識(shí)后,利用此類(lèi)來(lái)操作excel就清晰了很多。
三、Excel的操作
任何操作Excel的動(dòng)作首先肯定是用excel應(yīng)用程序,首先要new一個(gè)ApplicationClass 實(shí)例,并在最后將此實(shí)例釋放。
ApplicationClass xlsApp = new ApplicationClass(); // 1. 創(chuàng)建Excel應(yīng)用程序?qū)ο蟮囊粋€(gè)實(shí)例,相當(dāng)于我們從開(kāi)始菜單打開(kāi)Excel應(yīng)用程序。
if (xlsApp == null)
{
//對(duì)此實(shí)例進(jìn)行驗(yàn)證,如果為null則表示運(yùn)行此代碼的機(jī)器可能未安裝Excel
}
1. 打開(kāi)現(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; //第一個(gè)sheet頁(yè)
mySheet.Name = "testsheet"; //這里修改sheet名稱(chēng)
2.復(fù)制sheet頁(yè)
mySheet.Copy(Type.Missing, workbook.Sheets[1]); //復(fù)制mySheet成一個(gè)新的sheet頁(yè),復(fù)制完后的名稱(chēng)是mySheet頁(yè)名稱(chēng)后加一個(gè)(2),這里就是testsheet(2),復(fù)制完后,Worksheet的數(shù)量增加一個(gè)
注意 這里Copy方法的兩個(gè)參數(shù),指是的復(fù)制出來(lái)新的sheet頁(yè)是在指定sheet頁(yè)的前面還是后面,上面的例子就是指復(fù)制的sheet頁(yè)在第一個(gè)sheet頁(yè)的后面。
3.刪除sheet頁(yè)
xlsApp.DisplayAlerts = false; //如果想刪除某個(gè)sheet頁(yè),首先要將此項(xiàng)設(shè)為fasle。
(xlsApp.ActiveWorkbook.Sheets[1] as Worksheet).Delete();
4.選中sheet頁(yè)
(xlsApp.ActiveWorkbook.Sheets[1] as Worksheet).Select(Type.Missing); //選中某個(gè)sheet頁(yè)
5.另存excel文件
workbook.Saved = true;
workbook.SaveCopyAs(filepath);
6.釋放excel資源
workbook.Close(true, Type.Missing, Type.Missing);
workbook = null;
xlsApp.Quit();
xlsApp = null;
一般的我們傳入一個(gè)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;
}
我們調(diào)用如下:
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的指定位置加入文本框,和里面的內(nèi)容.
我們可以這樣來(lái)設(shè)計(jì)一個(gè)ExcelBase的基類(lèi):
先創(chuàng)建一個(gè)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; }
}
}
接下來(lái)創(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();
}
}
}
調(diào)用的代碼如下:
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);
}

- 比較2個(gè)datatable內(nèi)容是否相同的方法
- c#將list類(lèi)型轉(zhuǎn)換成DataTable方法示例
- 多個(gè)jquery.datatable共存,checkbox全選異常的快速解決方法
- DataTables List互相轉(zhuǎn)換的實(shí)現(xiàn)類(lèi)示例
- 使用DataTable.Select 方法時(shí),特殊字符的轉(zhuǎn)義方法分享
- ASP.NET中DataTable與DataSet之間的轉(zhuǎn)換示例
- 多個(gè)datatable共存造成多個(gè)表格的checkbox都被選中
- 將DataTable作為存儲(chǔ)過(guò)程參數(shù)的用法實(shí)例詳解
- datatable行轉(zhuǎn)列示例分享
相關(guān)文章
C#實(shí)現(xiàn)將窗體固定在顯示器的左上角且不能移動(dòng)的方法
這篇文章主要介紹了C#實(shí)現(xiàn)將窗體固定在顯示器的左上角且不能移動(dòng)的方法,涉及C#窗體固定操作的相關(guān)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-08-08C#實(shí)現(xiàn)繪制浮雕圖片效果實(shí)例
這篇文章主要介紹了C#實(shí)現(xiàn)繪制浮雕圖片效果實(shí)例,是C#程序設(shè)計(jì)中非常實(shí)用的一個(gè)功能,需要的朋友可以參考下2014-08-08C#中實(shí)現(xiàn)任意List的全組合算法代碼
這篇文章主要是介紹了.net C# 實(shí)現(xiàn)任意List的全組合算法實(shí)現(xiàn)代碼,需要的朋友可以參考下2013-05-05C# 通過(guò)同步和異步實(shí)現(xiàn)優(yōu)化做早餐的時(shí)間
本文以一個(gè)簡(jiǎn)單的小例子—如何做一頓早餐及如何優(yōu)化做早餐的時(shí)間來(lái)讓大家具體了解一下同步和異步方法的區(qū)別,需要的朋友可以參考一下2021-12-12c#多線(xiàn)程之間的排他鎖的實(shí)現(xiàn)
我們很多時(shí)候會(huì)碰到這樣的問(wèn)題,使用多線(xiàn)程刷一個(gè)表的數(shù)據(jù)時(shí)需要多個(gè)線(xiàn)程不能重復(fù)提取數(shù)據(jù),那么這個(gè)時(shí)候就需要使用到線(xiàn)程的排他鎖了,本文就詳細(xì)的介紹一下2021-08-08C#影院售票系統(tǒng)畢業(yè)設(shè)計(jì)(3)
這篇文章介紹了C#影院售票系統(tǒng)畢業(yè)設(shè)計(jì),文章主要內(nèi)容是關(guān)于購(gòu)票、座位顏色狀態(tài)的改變及場(chǎng)次座位狀態(tài)的顯示,需要的朋友可以參考下2015-11-11C#如何提取經(jīng)緯度文件中的經(jīng)緯度數(shù)據(jù)
近期開(kāi)發(fā)時(shí)需要獲取當(dāng)前的經(jīng)緯度坐標(biāo),下面這篇文章主要給大家介紹了關(guān)于C#如何提取經(jīng)緯度文件中經(jīng)緯度數(shù)據(jù)的相關(guān)資料,文中通過(guò)圖文介紹的非常詳細(xì),需要的朋友可以參考下2022-08-08