C# 报警操作(发出声音——bee~~~~)有用的小程序 winform
using System.Runtime.InteropServices;
[DllImport("kernel32.dll")]
private static extern int Beep(int dwFreq, int dwDuration);
private void button1_Click(object sender, EventArgs e)
{
int a = 0X7FF;
int b = 1000;
Beep(a, b);
}
c#经典常用小函数 winform
public class Utils
{
public static int GetStringLength(string str)
{//计算字符串字节长度
return Encoding.Default.GetBytes(str).Length;
}
/*
public static string Trim(string str)
{
if (str.Substring(0, 1) == " ")
{
for (int i = 0; i < str.Length; i++)
{
if (str.Substring(i, 1) == " ")
{
str = str.Remove(i, 1);
}
else
{
break;
}
}
}
if (str.Substring((str.Length - 1), 1) == " ")
{
for (int i = (str.Length - 1); i >= 0; i--)
{
if (str.Substring(i, 1) == " ")
{
str = str.Remove(i, 1);
}
else
{
break;
}
}
}
return str;
}*/
public static string Trim(string str) //去除前后空格
{
return new Regex("^ //s*|//s*$").Replace(str, "");
}
public static string Cut_str(string str, int len)
{//截取指定长度字符
int _a = 0;
int _b = 0;
string _s = "";
for (int _i = 0; _i < str.Length; _i++)
{
_b += 1;
if (new Regex("^[//u4E00-//u9FAF]+$").IsMatch(str.Substring(_i, 1)))
{
_a += 2;
}
else
{
_a++;
}
if (_a == len)
{
_s = str.Substring(0, _b);
break;
}
else if (_a > len)
{
_s = str.Substring(0, (_b - 1)) + ".";
break;
}
}
return _s;
}
public static string Ubb(string str)
{//ubb转换代码,.*虽然能匹配所有但是还要加上 ?贪婪模式 否则会出现点小问题
str = Regex.Replace(str, "//[b//](.*?)//[///b//]", "$1");
str = Regex.Replace(str, "//[u//](.*?)//[///u//]", "$1");
str = Regex.Replace(str, "//[i//](.*?)//[///i//]", "$1");
str = Regex.Replace(str, "//[b//](.*?)//[///b//]", "$1");
str = Regex.Replace(str, "//[img//](.*?)//[///img//]", "");
str = Regex.Replace(str, "//[url=(.*?)//](.*?)//[
///url//]", "$2");
str = Regex.Replace(str, "//[align=(.*?)//](.*?)//[///align//]", "
est.Cookies[strName];
if (cookie == null)
{
cookie = new HttpCookie(strName);
}
cookie.Values[strKeyName] = strKeyValue;
HttpContext.Current.Response.AppendCookie(cookie);
}
public static void WriteCookie(string strName, string strKeyName, String strKeyValue, int expires)
{//写cookie值+2重载函数 加子键/值 过期时间分钟计算
HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
if (cookie == null)
{
cookie = new HttpCookie(strName);
}
cookie.Values[strKeyName] = strKeyValue;
cookie.Expires = DateTime.Now.AddMinutes(expires);
//这里过期时间能影响到所有该集合下所有子键的过期时间
HttpContext.Current.Response.AppendCookie(cookie);
}
public static string GetCookie(string strName)
{//读cookie值
if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null)
{
return HttpContext.Current.Request.Cookies[strName].Value.ToString();
}
return "";
}
public static string GetCookie(string strName,string strKeyName)
{//读cookie值+1重载,读取Cookie子键值
if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null&& HttpContext.Current.Request.Cookies[strName].Values[strKeyName] != null)
{
return HttpContext.Current.Request.Cookies[strName].Values[strKeyName].ToString();
}
return "";
}
public static void setFile(string str)
{
//把一个值写如文件,调试用
string strFile = @"E:/CandC++/c#/session事件/01.txt";//这是路径
FileStream fs = new FileStream(strFile, FileMode.Append, FileAccess.Write);
//这里Append是追加模式,但是只能写模式下用这个模式
StreamWriter sw = new StreamWriter(fs);//创建一个写字符串的流
sw.WriteLine(str);
sw.Close();//关闭流写入磁盘文件
}
//------------字段验证函数----------------
public static bool validateName(string str)
{
return new Regex("^[//u4E00-//u9FAF//w+]+$").IsMatch(str);
}
public static bool validateLoginName(string str)
{
return new Regex("^[//w_]+$").IsMatch(str);
}
public static bool validateEmail(string str)
{
return new Regex("^[//w_//-//.]+?@//w+?//-?//w*?//-?//w*?(//.//w+)+?$").IsMatch(str);
}
public static bool validateTel(string str)
{
return new Regex("(^(//d{4}//-)?//d{7,8}$)|(^1//d{10}$)").IsMatch(str);
}
public static bool IsNumber(string str)
{//判断是否数字
return new Regex("^[0-9]+?$").IsMatch(str);
}
//----------------Request操作类-------
------------
public static bool IsPost()
{//判断是否是POST传输
return HttpContext.Current.Request.HttpMethod.Equals("POST");
}
public static bool IsGet()
{
return HttpContext.Current.Request.HttpMethod.Equals("GET");
}
public static string GetFormString(string str)
{//因为取不到值Form或Querystring为null赋给其他数据类型出错所以这里更改下
if (HttpContext.Current.Request.Form[str] == null)
{
return "";
}
else
{
return HttpContext.Current.Request.Form[str].ToString();
}
}
public static string GetQueryString(string str)
{//获得查询字符串
if (HttpContext.Current.Request.QueryString[str] == null)
{
return "";
}
else
{
return HttpContext.Current.Request.QueryString[str].ToString();
}
}
public static string GetServerString(string str)
{//获得服务器变量值
if (HttpContext.Current.Request.ServerVariables[str] == null)
{
return "";
}
else
{
return HttpContext.Current.Request.ServerVariables[str].ToString();
}
}
public static int GetInt(string strName, int defValue)
{//根据不同类型返回整数
string str = "";
switch (defValue)
{
case 1:
if (Utils.GetFormString(strName) != "")
{
str=Utils.GetFormString(strName);
}
break;
case 2:
if (Utils.GetQueryString(strName) != "")
{
str = Utils.GetQueryString(strName);
}
break;
case 3:
if (Utils.GetServerString(strName) != "")
{
str = Utils.GetServerString(strName);
}
break;
default:
break;
}
if (str == "")
{
return 0;
}
else
{
return Int32.Parse(str);
}
}
public static string GetUrlReferrer()
{//获取上一页的连接地址
string str = "";
try
{
str = HttpContext.Current.Request.UrlReferrer.ToString();
//本页直接打开获取这个值就是一个异常,所以处理下
}
catch { }
return str;
}
public static string GetCurrentFullHost()
{//获得主机和端口号
HttpRequest request = HttpContext.Current.Request;
if (!request.Url.IsDefaultPort)
{
return string.Format("{0}:{1}", request.Url.Host, request.Url.Port.ToString());
}
return request.Url.Host;
}
public static string GetHost()
{//直接获得的主机头
return HttpContext.Current.Request.Url.Host;
}
public static string GetRawUrl()
{//获得当前请求的从虚拟目录开始的:URl如有查询字符串则也包括在内
return HttpContext.Current.Request.RawUrl;
}
public static string GetUrl()
{//获得当前请求从HTTp:// Url如有查询字符串,则也包括在内
return HttpContext.Current.Request.Url.ToString();
}
public static string GetPageName()
{//返回当前页名字
string[] urlArr = HttpContext.Current.Request.Url.AbsolutePath.Split('/');
//这里是 AbsolutePath是返回一个不到参数的URl路径,不过Split注意里面要用'/'字符,而不是双引号
return urlArr[urlArr.Length - 1].ToLower();
}
public static int GetParamCount()
{//返回表单参数的总个数,无则返回0
return HttpContext.Current.Request.Form.Count + HttpContext.Current.Request.QueryString.Count;
//两个参数加起来就好了
}
public static bool IsIP(string ip)
{//判断是否为IP
return Regex.IsMatch(ip, @"^((2[0-4]/d|25[0-5]|[01]?/d/d?)/.){3}(2[0-4]/d|25[0-5]|[01]?/d/d?)$");
}
public static string GetIP()
{//获取ID地址
string result = String.Empty;
result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (null == result || result == String.Empty)
{
result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
if (null == result || result == String.Empty)
{
result = https://www.doczj.com/doc/1e844062.html,erHostAddress;
}
if (null == result || result == String.Empty || !Utils.IsIP(result))
{
return "0.0.0.0";
}
return result;
}
//-------------时间函数---------------------------------------------
public static string GetTime()
{
return DateTime.Now.ToString("HH:mm:ss");
}
public static string GetDateTime()
{
return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
}
public static string GetDateTime(int relativeday)
{
//+1重载
//返回增加了relativeday数的时间,当然也可以用 AddHours 增加小时了,还有分秒等等。。
return DateTime.Now.AddDays(relativeday).ToString("yyyy-MM-dd HH:mm:ss");
}
public static int GetTimeSpan(DateTime Dt_1, DateTime Dt_2)
{//返回两个时间差,差为两数之间的总秒数
TimeSpan Dt_3 = Dt_1 - Dt_2;
int _day = Dt_3.Days;
int _hours = Dt_3.Hours;
int _minutes = Dt_3.Minutes;
int _seconds = Dt_3.Seconds;
return ((((((_day * 60) + _hours) * 60) + _minutes) * 60) + _
seconds);
}
public static DateTime GetDateTime(string str)
{
//用字符串来创建时间对象
string[] strArray = Regex.Split(str, "|:");
int _num = 1;
int _year = 0, _month = 0, _day = 0, _hours = 0, _minutes = 0, _seconds = 0;
for (int i = 0; i < strArray.Length; i++)
{
if (IsNumber(strArray[i]))
{
switch (_num)
{
case 1: _year = Int16.Parse(strArray[i]); break;
case 2: _month = Int16.Parse(strArray[i]); break;
case 3: _day = Int16.Parse(strArray[i]); break;
case 4: _hours = Int16.Parse(strArray[i]); break;
case 5: _minutes = Int16.Parse(strArray[i]); break;
case 6: _seconds = Int16.Parse(strArray[i]); break; default: break;
}
_num++;
}
}
if (_num >= 6)
{ //创建时间对象,否则就出错提示
return new DateTime(_year, _month, _day, _hours, _minutes, _seconds);
}
else
{
return new DateTime(1, 1, 1, 1, 1, 1);
}
}
一个C#操作Excel类,功能比较全。
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Microsoft.Office.Interop;
using Microsoft.Office.Core;
namespace ExcelEdit
{
///
/// ExcelEdit 的摘要说明
///
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 ExcelEdit()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
public void Create()//创建一个Excel对象
{
app = new Excel.Application();
wbs = app.Workbooks;
wb = wbs.Add(true);
}
public void Open(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.Miss
ing,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;
}
public Excel.Worksheet GetSheet(string SheetName)
//获取一个工作表
{
Excel.Worksheet s = (Excel.Worksheet)wb.Worksheets[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);
https://www.doczj.com/doc/1e844062.html, = 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];
https://www.doczj.com/doc/1e844062.html, = NewSheetName;
return s;
}
public Excel.Worksheet ReNameSheet(Excel.Worksheet Sheet, string NewSheetName)//重命名一个工作表二
{
https://www.doczj.com/doc/1e844062.html, = NewSheetName;
return Sheet;
}
public void SetCellValue(Excel.Worksheet ws, int x, int y, object value)
//ws:要设值的工作表 X行Y列 value 值
{
ws.Cells[x, y] = value;
}
public void SetCellValue(string ws, int x, int y, object 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, string name, Excel.Constants color, Excel.Constants HorizontalAlignment)
//设置一个单元格的属性 字体, 大小,颜色 ,对齐方式
{
name = "宋体";
size = 12;
color = Excel.Constants.xlAutomatic;
HorizontalAlignment = Excel.Constants.xlRight;
ws.get_Range(ws.Cells[Startx, Starty], ws.Cells[Endx, Endy])https://www.doczj.com/doc/1e844062.html, = name;
ws.get_Range(ws.Cells[Startx, Starty], ws.Cells[Endx, Endy]).Font.Size = size;
ws.get_Range(ws.Cells[Startx, Starty], ws.Cells[Endx, Endy]).Font.Color = color;
ws.get_Range(ws.Cells[Startx, Starty], ws.Cells[Endx, Endy]).HorizontalAlignment = HorizontalAlignment;
}
public void SetCellProperty(string wsn, int Startx, int Starty, int Endx, int Endy, int size, string name, Excel.Constants color, Excel.Constants HorizontalAlignment)
{
//name = "宋体";
//size = 12;
//color = Excel.Constants.xlAutomatic;
//HorizontalAlignment = Excel.Constants.xlRight;
Excel.Wor
ksheet ws = GetSheet(wsn);
ws.get_Range(ws.Cells[Startx, Starty], ws.Cells[Endx, Endy])https://www.doczj.com/doc/1e844062.html, = name;
ws.get_Range(ws.Cells[Startx, Starty], ws.Cells[Endx, Endy]).Font.Size = size;
ws.get_Range(ws.Cells[Startx, Starty], ws.Cells[Endx, Endy]).Font.Color = color;
ws.get_Range(ws.Cells[Startx, Starty], 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, MsoTriStat
e.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
{
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.Quit();
wb = null;
wbs = null;
app = null;
GC.Collect();
}
}
}
转载一个EXCEL操作类
/**
* Excel控制类
* 作者:王文斌
* 版本:bate2 2008-6-6
* 备注:部分方法未经测试,使用时请注意。新增复制模板方法。支持26列以上表格。
* 使用方法:确保已安装office03,并安装Excel的.net开发支持
* 引用com口dll
* */
using System;
using System.Reflection;
using Microsoft.Office.Interop.Excel;
using Microsoft.Office.Core;
using System.Drawing;
namespace WWBClassLib.Excel
{
///
/// ExcelClass 的摘要说明。
///
public class ExcelCtrl
{
///
/// 构建ExcelClass类
///
public ExcelCtrl()
{
this.m_objExcel = new Microsoft.Office.Interop.Excel.Application();
}
///
/// 构建ExcelClass类
///
/// Excel.Application
public ExcelCtrl(Microsoft.Office.Interop.Excel.Application objExcel)
{
this.m_objExcel = objExcel;
}
///
/// 列标号
///
private string AList = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
///
/// 获取描述区域的字符
///
///
///
///
public string GetAix(int x, int y)
{
char[] AChars = AList.ToCharArray();
int i = x % 26;
int j = x / 26;
//if (x >= 26) { return ""; }
string s = "";
if (j > 0)
{
s = s + AChars[j - 1].ToString() + AChars[i].ToString();
}
else
{
s = s + AChars[x - 1].ToString();
}
//s = s + AChars[x - 1].ToString();
s = s + y.ToString();
return s;
}
///
/// 获取当前活动Sheet的Range的值
///
///
///
///
public string GetRangeText(int y, int x)
{
Microsoft.Office.Interop.Excel.Range range = sheet.get_Range(
this.GetAix(x, y), miss);
return range.Text.ToString();
}
///
/// 给单元格赋值1
///
/// 行号
/// 列号
/// 对齐(CENTER、LEFT、RIGHT)
/// 值
public void setValue(int y, int x, string align, string text)
{
Microsoft.Office.Interop.Excel.Range range = sheet.get_Range(this.GetAix(x, y), miss);
range.set_Value(miss, text);
if (align.ToUpper() == "CENTER")
{
range.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
}
if (align.ToUpper() == "LEFT")
{
range.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;
}
if (align.ToUpper() == "RIGHT")
{
range.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignRight;
}
}
///
/// 给单元格赋值2
///
/// 行号
/// 列号
/// 值
public void setValue(int y, int x, string text)
{
Microsoft.Office.Interop.Excel.Range range = sheet.get_Range(this.GetAix(x, y), miss);
range.set_Value(miss, text);
}
///
/// 给单元格赋值3
///
/// 行号
/// 列号
/// 值
/// 字符格式
/// 颜色
public void setValue(int y, int x, string text, System.Drawing.Font font, System.Drawing.Color color)
{
this.setValue(x, y, text);
Microsoft.Office.Interop.Excel.Range range = sheet.get_Range(this.GetAix(x, y), miss);
range.Font.Size = font.Size;
range.Font.Bold = font.Bold;
range.Font.Color = color;
https://www.doczj.com/doc/1e844062.html, = https://www.doczj.com/doc/1e844062.html,;
range.Font.Italic = font.Italic;
range.Font.Underline = font.Underline;
}
///
/// 给单元格赋值4
///
/// 行号
/// 列号
/// 值
/// 字符格式
public void setValue(int y, int x, string text, float size)
{
this.setValue(x, y, text);
Microsoft.Office.Interop.Excel.Range range = sheet.get_Range(this.GetAix(x, y), miss);
range.Font.Size = size;
}
//public void CopeTo(string fromSheetName,string startCell,string endCell,string ToSheetName)
//{
// Microsoft.Office.Interop.Excel.Worksheet fromsheet = GetSheet(fromSheetName);
// Microsoft.Office.Interop.Excel.Worksheet tosheet = GetSheet(ToSheetName);
// Microsoft.Office.Interop.Excel.Range rangefrom = fromsheet.get_Range(startCell, endCell);
// Microsoft.Office.Interop.Excel.Range rangeto = tosheet.get_Range(startCell, endCell);
// //rangeto.Copy(rangefrom);
// tosheet.Paste(rangefrom, rangeto);
//}
///
/// 复制sheet
/// 修正完成,重命名即可
///
///
///
///
///
public void CopySheet(string fromSheetName, string ToSheetName)
{
Microsoft.Office.Interop.Excel.Worksheet fromsheet = GetSheet(fromSheetName);
fromsheet.Copy(fromsheet, miss);
ReNameSheet(fromSheetName + " (2)", ToSheetName);
}
///
/// 插入新行 将设定行拷贝,然后插入空行,再将设定行粘贴到新行上
///
/// 模板行号
public void insertRow(int y)
{
Microsoft.Office.Interop.Excel.Range range = sheet.get_Range(GetAix(1, y), GetAix(25, y));
range.Copy(miss);
range.Insert(Microsoft.Office.Interop.Excel.XlDirection.xlDown, miss);
range.get_Range(GetAix(1, y), GetAix(25, y));
range.Select();
sheet.Paste(miss, miss);
}
//public void insertCopyRow(int x1,int y1,int x2,int y2)
//{
// Microsoft.Office.Interop.Excel.Range range = sheet.get_Range(GetAix(1, y), GetAix(25, y));
// range.Copy(miss);
// range.Insert(Microsoft.Office.Interop.Excel.XlDirection.xlDown, miss);
// range.get_Range(GetAix(1, y), GetAix(25, y));
// range.Select();
// sheet.Paste(miss, miss);
//}
/////
///// 把剪切内容粘贴到指定区域
/////
public void past(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4)
{
Microsoft.Office.Interop.Excel.Range range = sheet.get_Range(GetAix(x1, y1), GetAix(x2, y2));
range.Copy(miss);
sheet.Paste(sheet.get_Range(this.GetAix(x3, y3), this.GetAix(x4, y4)), range);
}
///
/// 设置边框
///
///
///
///
///
///
public void setBorder(int x1, int y1, int x2, int y2, int Width)
{
Microsoft.Office.Interop.Excel.Range range = sheet.get_Range(this.GetAix(x1, y1), this.GetAix(x2, y2));
range.Borders.Weight = Width;
}
///
/// 合并单元格,并设置居中方式 测试有问题 修正
///
///
///
///
///
/// 居中方式:center,left,right
public void mergeCell(int x1, int y1, int x2, int y2, string align)
{
UniteCells(sheet, x1, y1, x2, y2);
Microsoft.Office.Interop.Excel.Range range = sheet.get_Range(this.GetAix(x1, y1), this.GetAix(x2, y2));
//range.Merge(true);
if (align.ToUpper() == "CENTER")
{
range.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
}
if (align.ToUpper() == "LEFT")
{
range.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;
}
if (align.ToUpper() == "RIGHT")
{
range.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignRight;
}
}
///
/// 获取Range区域
///
///
///
///
///
///
public Microsoft.Office.Interop.Excel.Range getRange(int x1, int y1
, int x2, int y2)
{
Microsoft.Office.Interop.Excel.Range range = sheet.get_Range(this.GetAix(x1, y1), this.GetAix(x2, y2));
return range;
}
private object miss = Missing.Value; //忽略的参数OLENULL
private Microsoft.Office.Interop.Excel.Application m_objExcel;//Excel应用程序实例
private Microsoft.Office.Interop.Excel.Workbooks m_objBooks;//工作表集合
private Microsoft.Office.Interop.Excel.Workbook m_objBook;//当前操作的工作表
private Microsoft.Office.Interop.Excel.Worksheet sheet;//当前操作的表格
///
/// 活动工作Sheet
///
public Microsoft.Office.Interop.Excel.Worksheet CurrentSheet
{
get
{
return sheet;
}
set
{
this.sheet = value;
}
}
///
/// 获取活动WorkBooks
///
public Microsoft.Office.Interop.Excel.Workbooks CurrentWorkBooks
{
get
{
return this.m_objBooks;
}
set
{
this.m_objBooks = value;
}
}
///
/// 获取活动WorkBook
///
public Microsoft.Office.Interop.Excel.Workbook CurrentWorkBook
{
get
{
return this.m_objBook;
}
set
{
this.m_objBook = value;
}
}
///
/// 打开Excel文件
///
/// 路径
public void OpenExcelFile(string filename)
{
UserControl(false);
m_objExcel.Workbooks.Open(filename, miss, miss, miss, miss, miss, miss, miss,
miss, miss, miss, miss, miss, miss, miss);
m_objBooks = (Microsoft.Office.Interop.Excel.Workbooks)m_objExcel.Workbooks;
m_objBook = m_objExcel.ActiveWorkbook;
sheet = (Microsoft.Office.Interop.Excel.Worksheet)m_objBook.ActiveSheet;
}
public void UserControl(bool usercontrol)
{
if (m_objExcel == null) { return; }
m_https://www.doczj.com/doc/1e844062.html,erControl = usercontrol
;
m_objExcel.DisplayAlerts = usercontrol;
m_objExcel.Visible = usercontrol;
}
///
/// 创建Excel文件
///
public void CreateExceFile()
{
UserControl(false);
m_objBooks = (Microsoft.Office.Interop.Excel.Workbooks)m_objExcel.Workbooks;
m_objBook = (Microsoft.Office.Interop.Excel.Workbook)(m_objBooks.Add(miss));
sheet = (Microsoft.Office.Interop.Excel.Worksheet)m_objBook.ActiveSheet;
}
///
/// Excel文件另存为
///
///
public void SaveAs(string FileName)
{
m_objBook.SaveAs(FileName, miss, miss, miss, miss,
miss, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
Microsoft.Office.Interop.Excel.XlSaveConflictResolution.xlLocalSessionChanges,
miss, miss, miss, miss);
//m_objBook.Close(false, miss, miss);
}
///
/// 释放Excel文件
///
public void ReleaseExcel()
{
m_objExcel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject((object)m_objExcel);
System.Runtime.InteropServices.Marshal.ReleaseComObject((object)m_objBooks);
System.Runtime.InteropServices.Marshal.ReleaseComObject((object)m_objBook);
System.Runtime.InteropServices.Marshal.ReleaseComObject((object)sheet);
m_objExcel = null;
m_objBooks = null;
m_objBook = null;
sheet = null;
GC.Collect();
}
/////////////////////////////////
public bool KillAllExcelApp()
{
try
{
if (m_objExcel != null) // isRunning是判断xlApp是怎么启动的flag.
{
m_objExcel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objExcel);
//释放COM组件,其实就是将其引用计数减1
//System.Diagnostics.Process theProc;
foreach (System.Diagnostics.Process theProc in System.Diagnostics.Process.GetProcessesByName("EXCEL"))
{
//先关闭图形窗口。如果关闭失败...有的时候在状态里看不到图形窗口的excel了,
//但是在进程里
仍然有EXCEL.EXE的进程存在,那么就需要杀掉它:p
if (theProc.CloseMainWindow() == false)
{
theProc.Kill();
}
}
m_objExcel = null;
return true;
}
}
catch
{
return false;
}
return true;
}
/////////////////////////////////////////////
///
/// 获取一个工作表
///
/// Sheet名
///
public Microsoft.Office.Interop.Excel.Worksheet GetSheet(string SheetName)
{
Microsoft.Office.Interop.Excel.Worksheet s = (Microsoft.Office.Interop.Excel.Worksheet)m_objBook.Worksheets[SheetName];
return s;
}
///
/// 添加一个工作表
///
///
///
public Microsoft.Office.Interop.Excel.Worksheet AddSheetWithReturn(string SheetName)
{
Microsoft.Office.Interop.Excel.Worksheet s = (Microsoft.Office.Interop.Excel.Worksheet)m_objBook.Worksheets.Add(Type.Missing, Type.Missing, Type.Missing, Type.Missing);
https://www.doczj.com/doc/1e844062.html, = SheetName;
return s;
}
///
/// 添加一个工作表
///
public void AddSheet(string SheetName)
{
Microsoft.Office.Interop.Excel.Worksheet s = (Microsoft.Office.Interop.Excel.Worksheet)m_objBook.Worksheets.Add(Type.Missing, Type.Missing, Type.Missing, Type.Missing);
https://www.doczj.com/doc/1e844062.html, = SheetName;
}
///
/// 删除一个工作表
///
///
public void DelSheet(string SheetName)
{
((Microsoft.Office.Interop.Excel.Worksheet)m_objBook.Worksheets[SheetName]).Delete();
}
///
/// 重命名工作表
///
/// 原名
/// 新名
///
public Microsoft.Office.Interop.Excel.Worksheet ReNameSheet(string OldSheetName, string NewSheetName)//重命名一个工作表一
{
Microsoft.Office.Interop.Excel.Worksheet s = (Microsoft.Office.Interop.Excel.Worksheet)m_objBook.Worksheets[OldSheetName];
https://www.doczj.com/doc/1e844062.html, = NewSheetName;
return s;
}
public Microsoft.Office.Interop.Excel.Worksheet ReNameSheet(Microsoft.Office.Interop.Excel.Worksheet Sheet, string NewSheetName)//重命名一个工作表二
{
https://www.doczj.com/doc/1e844062.html, = NewSheetName;
return Sheet;
}
///
/// 设置单元格值
///
///
///
///
///
public void SetCellValue(Microsoft.Office.Interop.Excel.Worksheet ws, int x, int y, object value)
{
ws.Cells[y, x] = value;
}
///
/// 设置单元格值
///
/// sheet名
///
///
///
public void SetCellValue(string ws, int x, int y, object value)
{
GetSheet(ws).Cells[y, x] = value;
}
public void SetCellProperty(Microsoft.Office.Interop.Excel.Worksheet ws, int Startx, int Starty, int Endx, int Endy, int size, string name, Microsoft.Office.Interop.Excel.Constants color, Microsoft.Office.Interop.Excel.Constants HorizontalAlignment)
//设置一个单元格的属性 字体, 大小,颜色 ,对齐方式
{
//name = "宋体";
//size = 12;
color = Microsoft.Office.Interop.Excel.Constants.xlAutomatic;
HorizontalAlignment = Microsoft.Office.Interop.Excel.Constants.xlRight;
ws.get_Range(ws.Cells[Starty, Startx], ws.Cells[Endy, Endx])https://www.doczj.com/doc/1e844062.html, = name;
ws.get_Range(ws.Cells[Starty, Startx], ws.Cells[Endy, Endx]).Font.Size = size;
ws.get_Range(ws.Cells[Starty, Startx], ws.Cells[Endy, Endx]).Font.Color = color;
ws.get_Range(ws.Cells[Starty, Startx], ws.Cells[Endy, Endx]).HorizontalAlignment = HorizontalAlignment;
}
///
/// 设置单元格属性
///
/// Sheet页名称
/// x1
/// y1
/// x2
/// y2
///
字体大小
/// 字体名称
/// 字体颜色
/// 对齐方式
public void SetCellProperty(string wsn, int Startx, int Starty, int Endx, int Endy, int size, string name, Microsoft.Office.Interop.Excel.Constants color, Microsoft.Office.Interop.Excel.Constants HorizontalAlignment)
{
//name = "宋体";
//size = 12;
//color = Excel.Constants.xlAutomatic;
//HorizontalAlignment = Excel.Constants.xlRight;
Microsoft.Office.Interop.Excel.Worksheet ws = GetSheet(wsn);
ws.get_Range(ws.Cells[Starty, Startx], ws.Cells[Endy, Endx])https://www.doczj.com/doc/1e844062.html, = name;
ws.get_Range(ws.Cells[Starty, Startx], ws.Cells[Endy, Endx]).Font.Size = size;
ws.get_Range(ws.Cells[Starty, Startx], ws.Cells[Endy, Endx]).Font.Color = color;
ws.get_Range(ws.Cells[Starty, Startx], ws.Cells[Endy, Endx]).HorizontalAlignment = HorizontalAlignment;
}
///
/// 设置单元格属性
///
/// Sheet页名称
/// x1
/// y1
/// x2
/// y2
/// 字体大小
/// 字体名称
/// 字体颜色名称(系统预定义颜色)
/// 对齐方式
public void SetCellProperty(string wsn, int Startx, int Starty, int Endx, int Endy, int size, string name, string colorName, string HorizontalAlignment)
{
//name = "宋体";
//size = 12;
//color = Excel.Constants.xlAutomatic;
//HorizontalAlignment = Excel.Constants.xlRight;
Microsoft.Office.Interop.Excel.Worksheet ws = GetSheet(wsn);
ws.get_Range(ws.Cells[Starty, Startx], ws.Cells[Endy, Endx])https://www.doczj.com/doc/1e844062.html, = name;
ws.get_Range(ws.Cells[Starty, Startx], ws.Cells[Endy, Endx]).Font.Size = size;
Color color = Color.FromName(colorName);
color = Color.FromArgb(color.B, color.G, color.R);
ws.get_Range(ws.Cells[Starty, Startx], ws.Cells[Endy, Endx]).Font.Color = color.ToArgb();
if (HorizontalAlignment.ToUpper() == "CENTER")
{
ws.get_Range(ws.Cells[Starty, Sta
rtx], ws.Cells[Endy, Endx]).HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter; ;
}
if (HorizontalAlignment.ToUpper() == "LEFT")
{
ws.get_Range(ws.Cells[Starty, Startx], ws.Cells[Endy, Endx]).HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;
}
if (HorizontalAlignment.ToUpper() == "RIGHT")
{
ws.get_Range(ws.Cells[Starty, Startx], ws.Cells[Endy, Endx]).HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignRight;
}
}
///
/// 设置单元格底色
///
/// sheet页名称
/// x1
/// y1
/// x2
/// y2
/// 系统颜色名称
public void SetBorderColor(string wsn, int Startx, int Starty, int Endx, int Endy, string colorName)
{
Color color = Color.FromName(colorName);
color = Color.FromArgb(color.B, color.G, color.R);
Microsoft.Office.Interop.Excel.Worksheet ws = GetSheet(wsn);
ws.get_Range(ws.Cells[Starty, Startx], ws.Cells[Endy, Endx]).Cells.Interior.Color = color.ToArgb();
ws.get_Range(ws.Cells[Starty, Startx], ws.Cells[Endy, Endx]).Cells.Interior.Pattern = Microsoft.Office.Interop.Excel.XlBackground.xlBackgroundAutomatic;
}
//合并单元格 测试ok
public void UniteCells(Microsoft.Office.Interop.Excel.Worksheet ws, int x1, int y1, int x2, int y2)
{
ws.get_Range(ws.Cells[y1, x1], ws.Cells[y2, x2]).Merge(Type.Missing);
}
//合并单元格 测试ok
public void UniteCells(string ws, int x1, int y1, int x2, int y2)
{
GetSheet(ws).get_Range(GetSheet(ws).Cells[y1, x1], GetSheet(ws).Cells[y2, x2]).Merge(Type.Missing);
}
//将内存中数据表格插入到Excel指定工作表的指定位置 为在使用模板时控制格式时使用一
public void InsertTable(System.Data.DataTable dt, string ws, int startX, int startY)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
GetSheet(ws).Cells[startY + i, j + startX] = dt.Rows[i][j].ToString();
}
}
}
//将内存中数据表格插入到Excel指定工作表的指定位置二
public void InsertTable(System.Data.DataTable dt, Microsoft.Office.Interop.Excel.Worksheet ws, int startX, int startY)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
ws.Cells[startY + i, j + startX] = dt.Rows[i][j];
}
}
}
//插入图片操作一
public void InsertPictures(string Filename, string ws, int x, int y, int wight, int lenth)
{
//后面的数字表示位置
GetSheet(ws).Shapes.AddPicture(Filename, MsoTriState.msoFalse, MsoTriState.msoTrue, x, y, wight, lenth);
}
//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;
//}
}
}