using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Configuration;
using System.Web;
using Microsoft.Office.Interop;
using Excel = Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
using System.IO;
namespace ft_parser.code
{
///
/// Excel操作類,可以在後臺打開並操作Excel文件,並靜默保存,保存結束后會關閉對應進程。
///
/// 注意:如果後臺的Excel太多,可能會彈出提示,這時把那些後臺綫程關閉即可
///
public class ExcelEdit
{
public string mFilename;
public Excel.Application app;
public Excel.Workbooks wbs;
public Excel.Workbook wb;
public Excel.Worksheets wss;
public Excel.Worksheet ws;
public int m_iIsCreate = 0;//如果為1,則是創建文件
public ExcelEdit()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
public void Create()//创建一个Excel对象
{
app = new Excel.Application();
wbs = app.Workbooks;
app.Visible = false; //後臺執行可能需要這條,但有了 app.DisplayAlerts = false;好像又不用了。
//wb = wbs.Add(true);
}
///
/// 打開指定文件(目錄+文件名),如果不存在,則創建(指定目錄必須存在)
///
///
public void Open(string FileName)//打开一个Excel文件
{
if( app == null)
{
app = new Excel.Application();
wbs = app.Workbooks;
}
if (File.Exists(FileName))
{
try
{
wb = app.Workbooks.Open(FileName,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing);
//wb = wbs.Add(FileName);
//wb = wbs.Open(FileName, 0, true, 5,"", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true,Type.Missing,Type.Missing);
//wb = wbs.Open(FileName,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Excel.XlPlatform.xlWindows,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing);
}
catch (Exception ex)
{
#if DEBUG
Console.Write(FileName + "無法打開,改爲創建.");
#endif
m_iIsCreate = 1;
//string str = @"D:\data.xlsx";
wb = wbs.Add(true);
ws = app.Worksheets.Add();
}
}
else
{
m_iIsCreate = 1;
//string str = @"D:\data.xlsx";
wb = wbs.Add(true);
ws = app.Worksheets.Add();
}
mFilename = FileName;
}
public void CreateFile(string FileName)//打开一个Excel文件
{
app = new Excel.Application();
wbs = app.Workbooks;
wb = wbs.Add(FileName);
//wb = wbs.Open(FileName, 0, true, 5,"", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true,Type.Missing,Type.Missing);
//wb = wbs.Open(FileName,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Excel.XlPlatform.xlWindows,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing);
mFilename = FileName;
}
///
/// 獲取指定名稱的工作表,如果不存在,則獲取指定位置的工作表,並改名
///
/// 要獲取的工作表名
/// Sheet位置,默認1(指:Sheet1)
///
public Excel.Worksheet GetSheet(string SheetName, int iPos = 1)//获取一个工作表
{
Excel.Worksheet s;
try
{
s = (Excel.Worksheet)wb.Worksheets[SheetName];
}
catch(Exception ex)
{
s = (Microsoft.Office.Interop.Excel.Worksheet)wb.Sheets[iPos];
s.Name = SheetName;
}
return s;
}
public Excel.Worksheet AddSheet(string SheetName)//添加一个工作表
{
Excel.Worksheet s = (Excel.Worksheet)wb.Worksheets.Add(Type.Missing, Type.Missing, Type.Missing, Type.Missing);
s.Name = SheetName;
return s;
}
public void DelSheet(string SheetName)//删除一个工作表
{
((Excel.Worksheet)wb.Worksheets[SheetName]).Delete();
}
public Excel.Worksheet ReNameSheet(string OldSheetName, string NewSheetName)//重命名一个工作表一
{
Excel.Worksheet s = (Excel.Worksheet)wb.Worksheets[OldSheetName];
s.Name = NewSheetName;
return s;
}
public Excel.Worksheet ReNameSheet(Excel.Worksheet Sheet, string NewSheetName)//重命名一个工作表二
{
Sheet.Name = NewSheetName;
return Sheet;
}
public void SetCellValue(Excel.Worksheet ws, int x, int y, string value)//ws:要设值的工作表 X行Y列 value 值
{
ws.Cells[x, y] = value;
}
public void SetCellValue(string ws, int x, int y, string value)//ws:要设值的工作表的名称 X行Y列 value 值
{
GetSheet(ws).Cells[x, y] = value;
}
//设置一个单元格的属性 字体, 大小,颜色 ,对齐方式
public void SetCellProperty(Excel.Worksheet ws, int Startx, int Starty, int Endx, int Endy, int size =12, string name = "宋体", Excel.Constants color = Excel.Constants.xlAutomatic, Excel.Constants HorizontalAlignment = Excel.Constants.xlRight)
{
//name = "宋体";
//size = 12;
//color = Excel.Constants.xlAutomatic;
//HorizontalAlignment = Excel.Constants.xlRight;
ws.get_Range((Excel.Range)ws.Cells[Startx, Starty], (Excel.Range)ws.Cells[Endx, Endy]).Font.Name = name;
ws.get_Range((Excel.Range)ws.Cells[Startx, Starty], (Excel.Range)ws.Cells[Endx, Endy]).Font.Size = size;
ws.get_Range((Excel.Range)ws.Cells[Startx, Starty], (Excel.Range)ws.Cells[Endx, Endy]).Font.Color = color;
ws.get_Range((Excel.Range)ws.Cells[Startx, Starty], (Excel.Range)ws.Cells[Endx, Endy]).HorizontalAlignment = HorizontalAlignment;
}
///
/// 設置字體大小
///
///
///
///
///
///
///
public void SetCellSize(Excel.Worksheet ws, int Startx, int Starty, int Endx, int Endy, int size = 12)
{
ws.get_Range((Excel.Range)ws.Cells[Startx, Starty], (Excel.Range)ws.Cells[Endx, Endy]).Font.Size = size;
}
///
/// 設置字體
///
///
///
///
///
///
///
public void SetCellName(Excel.Worksheet ws, int Startx, int Starty, int Endx, int Endy, string name = "宋体")
{
ws.get_Range((Excel.Range)ws.Cells[Startx, Starty], (Excel.Range)ws.Cells[Endx, Endy]).Font.Name = name;
}
///
/// 設置是否粗體
///
///
///
///
///
///
///
public void SetCellBold(Excel.Worksheet ws, int Startx, int Starty, int Endx, int Endy, bool isBold = true)
{
ws.get_Range((Excel.Range)ws.Cells[Startx, Starty], (Excel.Range)ws.Cells[Endx, Endy]).Font.Bold = isBold;
}
public void SetCellColumnWidth(Excel.Worksheet ws, int Startx, int Starty, int Endx, int Endy, int iColumnWidth)
{
ws.get_Range((Excel.Range)ws.Cells[Startx, Starty], (Excel.Range)ws.Cells[Endx, Endy]).ColumnWidth = iColumnWidth;//設置列寬
}
///
/// 設置 居左 居右
///
///
///
///
///
///
/// Excel.XlHAlign.xlHAlignLeft 居左
public void SetCellHorizontalAlignment(Excel.Worksheet ws, int Startx, int Starty, int Endx, int Endy, Excel.XlHAlign HorizontalAlignment)
{
ws.get_Range((Excel.Range)ws.Cells[Startx, Starty], (Excel.Range)ws.Cells[Endx, Endy]).HorizontalAlignment = HorizontalAlignment;// Excel.XlHAlign.xlHAlignLeft
}
public void SetCellColor(Excel.Worksheet ws, int Startx, int Starty, int Endx, int Endy, int iIndex = 0)
{ //0無色, 1黑色,2白色,3紅色,4綠色,5藍色,6黃色,7紫色,8淺藍色,
//ws.get_Range((Excel.Range)ws.Cells[Startx, Starty], (Excel.Range)ws.Cells[Endx, Endy]).Interior.Color = color;//Excel.Constants color = Excel.Constants.xlAutomatic
ws.get_Range((Excel.Range)ws.Cells[Startx, Starty], (Excel.Range)ws.Cells[Endx, Endy]).Interior.ColorIndex = iIndex;
}
public void SetCellFontColor(Excel.Worksheet ws, int Startx, int Starty, int Endx, int Endy, int iIndex = 0)
{ //0無色, 1黑色,2白色,3紅色,4綠色,5藍色,6黃色,7紫色,8淺藍色,
//ws.get_Range((Excel.Range)ws.Cells[Startx, Starty], (Excel.Range)ws.Cells[Endx, Endy]).Interior.Color = color;//Excel.Constants color = Excel.Constants.xlAutomatic
ws.get_Range((Excel.Range)ws.Cells[Startx, Starty], (Excel.Range)ws.Cells[Endx, Endy]).Font.ColorIndex = iIndex;
}
public void SetCellProperty(string wsn, int Startx, int Starty, int Endx, int Endy, int size, string name, Excel.Constants color, Excel.XlHAlign HorizontalAlignment)
{
//name = "宋体";
//size = 12;
//color = Excel.Constants.xlAutomatic;
//HorizontalAlignment = Excel.Constants.xlRight;
Excel.Worksheet ws = GetSheet(wsn);
ws.get_Range((Excel.Range)ws.Cells[Startx, Starty], (Excel.Range)ws.Cells[Endx, Endy]).Font.Name = name;
ws.get_Range((Excel.Range)ws.Cells[Startx, Starty], (Excel.Range)ws.Cells[Endx, Endy]).Font.Size = size;
ws.get_Range((Excel.Range)ws.Cells[Startx, Starty], (Excel.Range)ws.Cells[Endx, Endy]).Font.Color = color;
ws.get_Range((Excel.Range)ws.Cells[Startx, Starty], (Excel.Range)ws.Cells[Endx, Endy]).HorizontalAlignment = HorizontalAlignment;
}
public void UniteCells(Excel.Worksheet ws, int x1, int y1, int x2, int y2)//合并单元格
{
ws.get_Range(ws.Cells[x1, y1], ws.Cells[x2, y2]).Merge(Type.Missing);
}
public void UniteCells(string ws, int x1, int y1, int x2, int y2)//合并单元格
{
GetSheet(ws).get_Range(GetSheet(ws).Cells[x1, y1], GetSheet(ws).Cells[x2, y2]).Merge(Type.Missing);
}
public void InsertTable(System.Data.DataTable dt, string ws, int startX, int startY)//将内存中数据表格插入到Excel指定工作表的指定位置 为在使用模板时控制格式时使用一
{
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
for (int j = 0; j <= dt.Columns.Count - 1; j++)
{
GetSheet(ws).Cells[startX + i, j + startY] = dt.Rows[i][j].ToString();
}
}
}
public void InsertTable(System.Data.DataTable dt, Excel.Worksheet ws, int startX, int startY)//将内存中数据表格插入到Excel指定工作表的指定位置二
{
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
for (int j = 0; j <= dt.Columns.Count - 1; j++)
{
ws.Cells[startX + i, j + startY] = dt.Rows[i][j];
}
}
}
public void AddTable(System.Data.DataTable dt, string ws, int startX, int startY)//将内存中数据表格添加到Excel指定工作表的指定位置一
{
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
for (int j = 0; j <= dt.Columns.Count - 1; j++)
{
GetSheet(ws).Cells[i + startX, j + startY] = dt.Rows[i][j];
}
}
}
public void AddTable(System.Data.DataTable dt, Excel.Worksheet ws, int startX, int startY)//将内存中数据表格添加到Excel指定工作表的指定位置二
{
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
for (int j = 0; j <= dt.Columns.Count - 1; j++)
{
ws.Cells[i + startX, j + startY] = dt.Rows[i][j];
}
}
}
//public void InsertPictures(string Filename, string ws)//插入图片操作一
//{
// GetSheet(ws).Shapes.AddPicture(Filename, MsoTriState.msoFalse, MsoTriState.msoTrue, 10, 10, 150, 150);//后面的数字表示位置
//}
//public void InsertPictures(string Filename, string ws, int Height, int Width)//插入图片操作二
//{
// GetSheet(ws).Shapes.AddPicture(Filename, MsoTriState.msoFalse, MsoTriState.msoTrue, 10, 10, 150, 150);
// GetSheet(ws).Shapes.get_Range(Type.Missing).Height = Height;
// GetSheet(ws).Shapes.get_Range(Type.Missing).Width = Width;
//}
//public void InsertPictures(string Filename, string ws, int left, int top, int Height, int Width)//插入图片操作三
//{
// GetSheet(ws).Shapes.AddPicture(Filename, MsoTriState.msoFalse, MsoTriState.msoTrue, 10, 10, 150, 150);
// GetSheet(ws).Shapes.get_Range(Type.Missing).IncrementLeft(left);
// GetSheet(ws).Shapes.get_Range(Type.Missing).IncrementTop(top);
// GetSheet(ws).Shapes.get_Range(Type.Missing).Height = Height;
// GetSheet(ws).Shapes.get_Range(Type.Missing).Width = Width;
//}
//插入图表操作
public void InsertActiveChart(Excel.XlChartType ChartType, string ws, int DataSourcesX1, int DataSourcesY1, int DataSourcesX2, int DataSourcesY2, Excel.XlRowCol ChartDataType)
{
ChartDataType = Excel.XlRowCol.xlColumns;
wb.Charts.Add(Type.Missing, Type.Missing, Type.Missing, Type.Missing);
{
wb.ActiveChart.ChartType = ChartType;
wb.ActiveChart.SetSourceData(GetSheet(ws).get_Range(GetSheet(ws).Cells[DataSourcesX1, DataSourcesY1], GetSheet(ws).Cells[DataSourcesX2, DataSourcesY2]), ChartDataType);
wb.ActiveChart.Location(Excel.XlChartLocation.xlLocationAsObject, ws);
}
}
public bool Save()//保存文档
{
if (mFilename == "")
{
return false;
}
else
{
try
{
if(m_iIsCreate == 1)
{
//ws.SaveAs(mFilename);//wb.SaveAs也可以
//wb.Save();
wb.SaveAs(mFilename, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
}
else
{
wb.Save();
}
return true;
}
catch (Exception ex)
{
return false;
}
}
}
public bool SaveAs(object FileName)//文档另存为
{
try
{
wb.SaveAs(FileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
return true;
}
catch (Exception ex)
{
return false;
}
}
public void Close()//关闭一个Excel对象,销毁对象
{
//wb.Save();
wb.Close(Type.Missing, Type.Missing, Type.Missing);
wbs.Close();
app.DisplayAlerts = false;//後臺執行
app.Quit();
Kill(app);
System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
wb = null;
wbs = null;
app = null;
//GC.Collect();
}
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID);
public static void Kill(Microsoft.Office.Interop.Excel.Application excel)
{
IntPtr t = new IntPtr(excel.Hwnd);//得到这个句柄,具体作用是得到这块内存入口
int k = 0;
GetWindowThreadProcessId(t, out k); //得到本进程唯一标志k
System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k); //得到对进程k的引用
p.Kill(); //关闭进程k
}
}
}
調用方法:
ExcelEdit exl = new ExcelEdit();
//exl.Create();
exl.Open("D:\\data.xlsx");
Excel.Worksheet ws = exl.GetSheet("sheetname111");
exl.SetCellValue(ws, 1, 1, "name1");
exl.SetCellValue(ws, 1, 2, "value1");
exl.SetCellValue(ws, 2, 1, "name2");
exl.SetCellValue(ws, 2, 2, "value2");
exl.SetCellValue(ws, 3, 1, "name3");
exl.SetCellValue(ws, 3, 2, "value3");
//exl.SetCellColor(ws, 1, 1, 1, 2,0);
exl.SetCellSize(ws, 1, 1, 2, 1, 18);
exl.SetCellFontColor(ws, 1, 1, 2, 1, 3);
exl.SetCellBold(ws, 1, 1, 2, 1,true);
exl.Save();
exl.Close();