这里写目录标题
1、js的常用方法
1.1、在JavaScript使用xpath
function $x(STR_XPATH) {
var xresult = document.evaluate(STR_XPATH, document, null, XPathResult.ANY_TYPE, null);
var xnodes = [];
var xres;
while (xres = xresult.iterateNext()) {
xnodes.push(xres);
}
return xnodes;
}
实例:
document.getElementById("").click()
$x("div[@id='']")
1.2、javascript在iframe的使用
function _x(WINDOW, STR_XPATH) {
var xresult = WINDOW.evaluate(STR_XPATH, WINDOW, null, XPathResult.ANY_TYPE, null);
var xnodes = [];
var xres;
while (xres = xresult.iterateNext()) {
xnodes.push(xres);
}
return xnodes;
}
function get_models() {
var iframe_class = _x(document, '//iframe[contains(@class,"templateEditor-crowdpick-iframe")]/@class')[0].value;
var iframe = document.getElementsByClassName(iframe_class)[0].contentWindow.document;
var model_names = [];
var model_elems = _x(iframe, '//div[contains(@class,"src-ModuleBrand-crowdBox-topInfoItem")]');
for (var i = 0; i < model_elems.length; i++) {
model_names.push(model_elems[i].textContent);
}
return model_names;
}
1.3、javascript将HTMLCollection转换为数组
let arr=document.getElementById('box').getElementsByTagName('i')
console.log(arr)
将其转换为array类型
let arr=document.getElementById('box').getElementsByTagName('i')
//Array.from()方法就是将一个类数组对象或者可遍历对象转换成一个真正的数组。
arr=Array.from(arr)
console.log(arr)
1.4、JavaScript中的Array.prototype.slice.call的用法
JavaScript中的Array.prototype.slice.call(arguments)能将有length属性的对象转换为数组(特别注意: 这个对象一定要有length属性).
但有一个例外,IE下的节点集合它不能转换(因为IE下的dom对象是以com对象的形式实现,js对象和com对象不能进行转换)
function get_datas() {
var name_doms = Array.prototype.slice.call(document.getElementsByClassName("oui-index-cell-indexName"));
//将length属性装换为数组
var names = name_doms.map(function(e) {
return e.innerText
});
var value_doms = Array.prototype.slice.call(document.getElementsByClassName("oui-index-cell-indexValue"));
var values = value_doms.map(function(e) {
return e.innerText.replace(',', '')
});
var dataMap = {};
for (var k in names) {
dataMap[names[k]] = values[k];
}
return JSON.stringify(dataMap);
}
2、C#随机数的常用方法
2.1、C#获取一个范围内的随机数
static void Main(string[] args)
{
int a = randomPWD(10,100);
Console.WriteLine(a);
}
public static int randomPWD(int start,int end) {
Random rd = new Random();
return rd.Next(start, end);
}
2.2、C#获取一个String列表的随机数
static void Main(string[] args)
{
int a = randomPWD(10,100);
Console.WriteLine(a);
String[] pwdArray = new String[] { "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz", "1234567890" };
string str = randomstring(pwdArray);
Console.WriteLine(str);
}
public static string randomstring(string[] pwdArray) {
Random rd2 = new Random();
int b = rd2.Next(pwdArray.Length);
return pwdArray[b];
}
public static int randomPWD(int start, int end)
{
Random rd = new Random();
return rd.Next(start, end);
}
2.3、C#获取一个List列表的随机数
static void Main(string[] args)
{
(new Program()).Run();
}
public void Run()
{
List<string> pwd = new List<string>();
int c = test(pwd);
Console.WriteLine(pwd[c]);
}
public int test(List<string> pwd)
{
pwd.Add("ass");
pwd.Add("a1s");
Random rd2 = new Random();
int b = rd2.Next(pwd.Count);
return b;
}
2.4、C#随机获取string数据里面的一个char
public void Run()
{
string s = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Console.WriteLine(s.Length);
Array test1 = s.ToCharArray();
Random rdd = new Random();
int b1 = rdd.Next(s.Length);
Console.WriteLine(test1.GetValue(b1));
Console.WriteLine();
}
//类似的string[]
String[] pwdArray = new String[] { "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz", "1234567890" };
Random rd2 = new Random();
Console.WriteLine(pwdArray[0].GetType());
Array ls = pwdArray[0].ToString().ToCharArray(); //将string的字符串转换为charArray类型的数值
int b = rd2.Next(ls.Length);
Console.WriteLine(ls.GetValue(b)); //使用数组的时候使用getvalue获取相应的值。
3、C# datatabe的常用方法
3.1、将一个datatable里的行放到另一个datatable的行里。
public void Run()
{
int row = data_table.Rows.Count;
Console.WriteLine(row);
for (int j = 0; j < data_table.Columns.Count; j++) // 获取表的结构,可以直接配置一个表
{
data_table1.Columns.Add(data_table.Columns[j].ColumnName);//有重载的方法,可以加入列数据的类型
}
for(int i=0;i<row;i++){
Console.WriteLine(data_table.Rows[i].GetType());
//Console.WriteLine(data_table.Rows[i]["振幅"].ToString().Replace('%',""));
if(double.Parse(data_table.Rows[i]["振幅"].ToString().Replace("%","")) > 1.5){
DataRow drq = data_table1.NewRow(); //创建一个空表行,如果不创建一个空行就会出现该行是data_table的行,会报错转移不进去
drq.ItemArray = data_table.Rows[i].ItemArray; //将DataRow数据表添加到新的表格里
data_table1.Rows.Add(drq);
}
}
}
3.1.1、读取Datatable数据。
DataTable one = (new Cdatatable()).Createdatatable();
for(int i=0;i<one.Rows.Count;i++){
for(int j=0;j<one.Columns.Count;j++){
System.Console.WriteLine(one.Rows[i][j].ToString());
}
}
3.1.2、创建Datatable。
下列为一个例子如果不是在云扩使用则(要实例化datatable)
//代码执行入口,请勿修改或删除
public void Run()
{
one = test();
for(int i=0;i<one.Rows.Count;i++){
for(int j=0;j<one.Columns.Count;j++){
System.Console.WriteLine(one.Rows[i][j].ToString());
}
}
}
public DataTable test(){
dt = new DataTable();
DataColumn dc1 = new DataColumn("姓名",typeof(string));
DataColumn dc2 = new DataColumn("年龄",typeof(string));
DataColumn dc3 = new DataColumn("爱好",typeof(string));
DataColumn dc4 = new DataColumn("身高",typeof(string));
dt.Columns.Add(dc1);
dt.Columns.Add(dc2);
dt.Columns.Add(dc3);
dt.Columns.Add(dc4);
for(int i=0;i<10;i++)
{
DataRow dr=dt.NewRow();
dr["姓名"]="娃娃";
dr["年龄"]="10";
dr["爱好"]="1";
dr["身高"]="10";
dt.Rows.Add(dr);
}
return dt;
}
3.2、 DataTable和Excel的相互转换。
3.2.1、 DataTable转Excel。
using System;
using System.Data;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System.IO;
using NPOI.XSSF.UserModel;
namespace QingNiao
{
class DataTable_Excel
{
public void Createdatatable()
{
DataTable dt = new DataTable();
dt.Columns.Add("姓名", typeof(string));
dt.Columns.Add("年龄", typeof(string));
dt.Columns.Add("兴趣", typeof(string));
dt.Columns.Add("电源", typeof(string));
for(int i=0;i<10;i++)
{
dt.Rows.Add(new Object[] { "娃娃", "10", "1", "10" });
// 等同于
// DataRow dr=dt.NewRow();
// dr["姓名"]="娃娃";
// dr["年龄"]="10";
// dr["兴趣"]="1";
// dr["电源"]="10";
// dt.Rows.Add(dr);
}
ToExcel(dt,@"C:\Users\Administrator\Desktop\2.xlsx");
}
public void ToExcel(DataTable dt,string saveFilePath)
{
IWorkbook workbook = null;
if (saveFilePath != null)
{
if (saveFilePath.IndexOf(".xlsx") > 0)
{
workbook = new XSSFWorkbook();
}
else if (saveFilePath.IndexOf(".xls") > 0)
{
workbook = new HSSFWorkbook();
}
}
var count = 0;
for (double i = 0; i < Convert.ToDouble(dt.Rows.Count) / Convert.ToDouble(65534); i++)//每个Excel文件的一个页签只能存放65536行数据
{
var row_index = 0;
//创建Sheet
workbook.CreateSheet("Sheet" + i);
//根据Sheet名字获得Sheet对象
var sheet = workbook.GetSheet("Sheet" + i);
IRow row;
row = sheet.CreateRow(row_index);
//写入标题
for (int j = 0; j < dt.Columns.Count; j++)
{
row.CreateCell(j).SetCellValue(dt.Columns[j].Caption.ToString());
}
row = sheet.CreateRow(++row_index);
//写入数据
for (int j = 0; j < (dt.Rows.Count - count > 65534 ? 65534 : dt.Rows.Count - count); j++)
{
var r = dt.Rows[j + count];
for (int k = 0; k <dt.Columns.Count; k++)
{
row.CreateCell(k).SetCellValue(r[k].ToString());
}
row = sheet.CreateRow(++row_index);
}
count += row_index - 2;
}
//保存Workbook方式一: 以文件形式保存到服务器中(每次导出都会生成一个文件,慎重使用)
FileStream fs = new FileStream(saveFilePath,FileMode.OpenOrCreate,FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
workbook.Write(fs);
}
}
}
3.2.2、C# 读取excel至DataTable。
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using Newtonsoft.Json.Linq;
namespace json
{
class Excel_Tools
{
public static DataTable ReadFile(string excelPath, object sheetKey, bool hasTitle = true)
{
if (!System.IO.File.Exists(excelPath)) throw new Exception($"Excel文件不存在:{excelPath}");
string fileType = System.IO.Path.GetExtension(excelPath);
if (string.IsNullOrEmpty(fileType)) throw new Exception($"非有效的Excel文件:{excelPath}");
FileStream fsRead = new FileStream(excelPath, FileMode.Open, FileAccess.Read); // 打开文件
IWorkbook workbook = WorkbookFactory.Create(fsRead); // 打开工作簿
bool isInt = sheetKey.GetType().ToString().Equals("System.Int32"); // 判断表索引是否为int
ISheet worksheet = isInt ? workbook.GetSheetAt((int)sheetKey) : workbook.GetSheet((string)sheetKey); // 打开工作表
int max_row = worksheet.LastRowNum + 1; // 获取最大行号
// 读表构建DataTable
DataTable dtReadDatas = new DataTable();
if (max_row == 1) return dtReadDatas;
JArray FirstRowData = getRowDatas(worksheet.GetRow(0));
if (hasTitle)
{
foreach (string title in FirstRowData) dtReadDatas.Columns.Add(title);
}
else
{
for (int icol = 0; icol < FirstRowData.Count; icol++) dtReadDatas.Columns.Add($"列-{icol + 1}");
}
for (int k = hasTitle ? 1 : 0; k < max_row; k++)
{
JArray arrRowDatas = getRowDatas(worksheet.GetRow(k));
DataRow row = dtReadDatas.NewRow();
for (int icol = 0; icol < arrRowDatas.Count; icol++) row[icol] = arrRowDatas[icol];
dtReadDatas.Rows.Add(row);
}
//PrintDataTable(dtReadDatas);
RemoveEmpty(dtReadDatas);
return dtReadDatas;
}
//去除空行,主要的目的就是去除excel表中的空行
public static DataTable RemoveEmpty(DataTable dt)
{
List<DataRow> removelist = new List<DataRow>();
for (int i = 0; i < dt.Rows.Count; i++)
{
bool rowdataisnull = true;
for (int j = 0; j < dt.Columns.Count; j++)
{
if (!string.IsNullOrEmpty(dt.Rows[i][j].ToString().Trim()))
{
rowdataisnull = false;
}
}
if (rowdataisnull)
{
removelist.Add(dt.Rows[i]);
}
}
//移除空行
for (int i = 0; i < removelist.Count; i++)
{
dt.Rows.Remove(removelist[i]);
}
return dt;
}
static JArray getRowDatas(IRow currentRow)
{
JArray arrRowDatas = new JArray();
try
{
int max_col = currentRow.LastCellNum; // 获取当前行最大列
for (int k = 0; k < max_col; k++)
{
ICell cell = currentRow.GetCell(k); // 获取每一个表格的数据
//if (cell.ToString == null) continue;
//Console.WriteLine(cell.CellType);
if (cell.CellType == CellType.Formula) // CellType.Formula表示的是公式型2,如果是公式型就得转换为string类型。
{
cell.SetCellType(CellType.String); // 将每一个单元格的数据设置为string类型
arrRowDatas.Add(cell.StringCellValue); //获取string类型的数据
}
else
{
arrRowDatas.Add(cell.ToString());
}
}
}
catch (NullReferenceException) { }
return arrRowDatas;
}
//当excel数据表格是对的时,不会出现很多空行可以使用下面打印结果。
static void PrintDataTable(DataTable dtReadDatas)
{
List<string> cols = new List<string>();
foreach (DataColumn col in dtReadDatas.Columns) cols.Add(col.ToString());
Console.WriteLine(string.Join('\t', cols));
foreach (DataRow row in dtReadDatas.Rows)
{
Console.WriteLine(string.Join('\t', row.ItemArray));
}
Console.WriteLine("========================================");
}
}
}
3.2.3、C# 读取excel文件数据的每一行。
(1): Application对象。Application对象处于Excel对象层次结构的顶层,表示Excel自身的运行环境。
(2):Workbook对象。Workbook对象直接地处于Application对象的下层,表示一个Excel工作薄文件。
(3):Worksheet对象。Worksheet对象包含于Workbook对象,表示一个Excel工作表。
(4):Range对象。Range对象包含于Worksheet对象,表示Excel工作表中的一个或多个单元格。
NPOP的使用
NPOI 使用 HSSFWorkbook 类来处理 xls,
XSSFWorkbook 类来处理 xlsx,它们都继承接口IWorkbook,
因此可以通过 IWorkbook 来统一处理 xls 和 xlsx 格式的文件。
读取ecxcel表的每一行
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RestSharp;
using NPOI.HSSF.UserModel;
using System.Data;
using NPOI.SS.UserModel;
using System.IO;
using NPOI.XSSF.UserModel;
namespace QingNiao
{
class Program
{
static void Main(string[] args)
{
(new Program()).run();
}
public void run(){
ReadFromExcelFile(@"C:\账号批量改密\超管账号配置.xlsx");
}
public void ReadFromExcelFile(string filePath){
IWorkbook wk = null;
string extension = System.IO.Path.GetExtension(filePath); // 获取文件的后缀名
System.Console.WriteLine(extension);
try{
FileStream fs = File.OpenRead(filePath); // 打开现有文件以进行读取。
if(extension.Equals(".xls")){
//把xls文件中的数据写入wk中
wk = new HSSFWorkbook(fs);
}
else{
//把xlsx文件中的数据写入wk中
wk = new XSSFWorkbook(fs);
}
fs.Close();
//读取当前表数据
ISheet sheet = wk.GetSheetAt(0);
IRow row = sheet.GetRow(0); //读取当前行数据
Console.WriteLine(row);
//LastRowNum 是当前表的总行数-1(注意)
//int offset = 0;
for(int i =0;i<sheet.LastRowNum;i++)
{
row = sheet.GetRow(i); //获取当前行数据
if(row!=null)
{
for(int j=0;j<row.LastCellNum;j++) //LastCellNum 是当前行的总列数
{
//读取该行的第j列数据
string value = row.GetCell(j).ToString();
System.Console.WriteLine(value.ToString()+"");
}
System.Console.WriteLine("\n");
}
}
}
catch(Exception e){
System.Console.WriteLine(e.Message);
}
}
}
}
3.2.4、celltype的类型值。
CellType 类型 值 CELL_TYPE_NUMERIC 数值型 0
CELL_TYPE_STRING 字符串型 1
CELL_TYPE_FORMULA 公式型 2
CELL_TYPE_BLANK 空值 3
CELL_TYPE_BOOLEAN 布尔型 4
CELL_TYPE_ERROR 错误 5
3.3、文件处理
3.3.1、C# 判断文件或文件夹是否存在。
public string Judge_path()
{
//判断文件文件夹是否存在
if (!System.IO.Directory.Exists(@"C:\Users\Administrator\Desktop"))
{
//如果文件夹不存在则创建一个文件夹
System.IO.Directory.CreateDirectory(@"C:\Users\Administrator\Desktop");
return "文件不存在,但是已经创建";
}
else {
//Console.WriteLine("文件已存在");
return "文件已存在";
}
}
public string Judge_file()
{
//判断文件文件夹是否存在
if(File.Exists(@"C:\生意参谋店铺相关表格\2.xls"))
{
Console.WriteLine("文件存在");
}
else {
Console.WriteLine("文件不存在");
}
}
3.3.2、实例(判断文件名称时间与表内时间是否一致)。
在这里插入代码片
3.4、DataTable和JArray的转换
3.4.1、DataTable转JArray
public static JArray DataTableToJArray(DataTable dtReadDatas)
{
JArray tableDatas = new JArray();
// 读取表头
List<string> tiltles = new List<string>();
foreach (DataColumn col in dtReadDatas.Columns) tiltles.Add(col.ToString());
// 读取数据
foreach (DataRow row in dtReadDatas.Rows)
{
JObject rowData = new JObject();
for (int i = 0; i < tiltles.Count; i++)
{
rowData.Add(tiltles[i], row.ItemArray[i].ToString());
}
tableDatas.Add(rowData);
}
return tableDatas;
}
4、c# datetime的常用方法
4.1、datetime的使用
public void run(){
DateTime dt = DateTime.Now;
Console.Writeline(dt); //打印当前时间
Console.WriteLine(dt.Year); //打印当前的年份
Console.WriteLine(dt.Month); //打印当前的月份
Console.WriteLine(dt.Day); //打印当前的天数
Console.WriteLine(dt.ToString("yyyy-MM-dd")); //按yyyy-MM-dd格式输出s
Console.Writeline(spanday())
dt.AddDays(1); //增加一天 dt本身并不改变,另取变量赋值,或覆盖原值
dt.AddDays(-1);//减少一天 dt本身并不改变,另取变量赋值,或覆盖原值
Console.Writeline(changetime())
}
//跨越的时间
public int spanday()
{
DateTime dt1 = Convert.ToDateTime("2007-8-1");
DateTime dt2 = Convert.ToDateTime("2007-8-15");
TimeSpan span = dt2.Subtract(dt1);
int dayDiff = span.Days;
return dayDiff;
//Console.WriteLine(dayDiff);
}
//时间戳
public long changetime(){
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 当地时区
long timeStamp = (long)(DateTime.Now - startTime).TotalMilliseconds; // 相差毫秒数
//System.Console.WriteLine(timeStamp);
return timeStamp;
}
4.2、datetime时间戳的使用
using System;
using System.Data;
using System.IO;
using NOPI.HSSF.UserModel;
using NOPT.SS.UserMode;
namespace (控件名)
{
classCopyFile
{
public void Run()
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970,1,1,0,0,0,0);
string time_span = Convert.ToInt64(ts.TotalSeconds).ToString();
System.Console.WriteLine(time_span); //返回的是当前的时间戳
}
}
}
5、c# 三目运算
class Program
{
static void Main(string[] args)
{
// Console.WriteLine("Hello World!");
int a =5;
int b = 6;
string aa = a>b? "111":"222";
Console.WriteLine(aa);
// int sex=0;
// string sexText=sex==0 ? "女" : "男";
// Console.WriteLine(sexText);
}
}
6、c# JArray和JObject的使用
序列化的使用方法是:
string names = JsonConvert.SerializeObject() 括号里为JObject数据
反序列化的使用方法
JObject names =(JObject)JsonConvert.DeserializeObject(jsonText1)
6.1、c# 构建json数据:
这是一个excel表格:将其转换为一个json数据的配置表:
调用3.2.1的读取excel至datatable
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Data;
namespace json
{
class Seachs
{
public void Run()
{
DataTable result = Excel_Tools.ReadFile(@"C:\Users\Administrator\Desktop\修改编码-模版.xlsx", 0, true);
JObject objshopexcel = new JObject();
string currentId = ""; //先给定一个空值
foreach (DataRow row in result.Rows)
{
string shopids = row["商品ID"].ToString();
if (shopids.Length > 0) currentId = shopids;
JObject modify = new JObject();
if (currentId != null)
{
modify.Add("ID", row["商品ID"].ToString());
modify.Add("skuId", row["skuId【无sku商品则不填写】"].ToString());
modify.Add("原编码", row["原编码(选填)"].ToString());
modify.Add("新编码", row["新编码"].ToString());
}
if (objshopexcel.Property(currentId) == null) objshopexcel.Add(currentId, new JArray());
(objshopexcel[currentId] as JArray).Add(modify);
}
System.Console.WriteLine(objshopexcel);
foreach (JProperty objpro in objshopexcel.Properties())
{
Console.WriteLine(objpro.Name);
Console.WriteLine(objpro.Value);
}
}
}
}
6.2、c# 遍历JObject数据:
方法:JProperty 和 Jobject.Properties()
返回的是一个键值对
foreach (JProperty objpro in objshopexcel.Properties())
{
Console.WriteLine(objpro.Name); //获取key
Console.WriteLine(objpro.Value); //获取值
//JArray ChangeId = objpro.Value as JArray;
//Console.WriteLine(ChangeId);
for (int i = 0; i < ChangeId.Count; i++)
{
Console.WriteLine(ChangeId[i].ToString());
}
}
6.3、c# 遍历JArray数据:
foreach (JProperty objpro in objshopexcel.Properties())
{
//Console.WriteLine(objpro.Name); //获取key
//Console.WriteLine(objpro.Value); //获取值
JArray ChangeId = objpro.Value as JArray;
Console.WriteLine(ChangeId);
for (int i = 0; i < ChangeId.Count; i++)
{
Console.WriteLine(ChangeId[i].ToString());
}
}