iis服务器助手广告广告
返回顶部
首页 > 资讯 > 精选 >C#怎么调用js库
  • 362
分享到

C#怎么调用js库

2023-07-05 23:07:29 362人浏览 独家记忆
摘要

这篇文章主要介绍“C#怎么调用js库”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“C#怎么调用js库”文章能帮助大家解决问题。安装ClearScriptClearScript是微软开源的js引擎,支

这篇文章主要介绍“C#怎么调用js库”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“C#怎么调用js库”文章能帮助大家解决问题。

安装ClearScript

ClearScript是微软开源的js引擎,支持windowslinuxMac
NuGet搜索安装:

  • Microsoft.ClearScript.Core

  • Microsoft.ClearScript.V8

  • Microsoft.ClearScript.V8.Native.win-x64

引入js文件

C#怎么调用js库

把leaflet.mapCorrection.js、turf.v6.5.0.min.js和自己写的calc.js放入工程中,右击属性设置复制到输出目录:如果较新则复制。
calc.js通过调用leaflet.mapCorrection.js和turf.v6.5.0.min.js中的方法实现功能,文件内容如下:

function calc(lng, lat, polyGonStr) {    var point = turf.point([lng, lat]);    var polygonPoints = JSON.parse(polygonStr);    var polygon = turf.polygon(polygonPoints);    var bl = turf.booleanPointInPolygon(point, polygon);    return bl;}function correct(lng, lat) {    var newPoint = new CoordConvertor().GCj02_To_gps84(lng, lat);    return newPoint;}

创建V8ScriptEngine对象

private V8ScriptEngine _engine = new V8ScriptEngine();

通过js引擎加载js文件

在FORM1_Load方法中添加如下代码:

_engine.AddHostType("Console", typeof(Console));string fileName = AppDomain.CurrentDomain.BaseDirectory + "turf.v6.5.0.min.js";string js;using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)){    byte[] bArr = new byte[fs.Length];    await fs.ReadAsync(bArr, 0, bArr.Length);    js = ASCIIEncoding.UTF8.GetString(bArr);}_engine.Execute(js);fileName = AppDomain.CurrentDomain.BaseDirectory + "calc.js";using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)){    byte[] bArr = new byte[fs.Length];    await fs.ReadAsync(bArr, 0, bArr.Length);    js = ASCIIEncoding.UTF8.GetString(bArr);}_engine.Execute(js);fileName = AppDomain.CurrentDomain.BaseDirectory + "leaflet.mapCorrection.js";using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)){    byte[] bArr = new byte[fs.Length];    await fs.ReadAsync(bArr, 0, bArr.Length);    js = ASCIIEncoding.UTF8.GetString(bArr);}_engine.Execute(js);

C#调用js方法实现经纬度坐标纠偏

double lng = Convert.ToDouble(lnglat[0]);double lat = Convert.ToDouble(lnglat[1]);//坐标纠偏dynamic newPoint = _engine.Invoke("correct", new object[] { lng, lat });lng = newPoint.lng;lat = newPoint.lat;

C#调用js方法判断经纬度点位是否在多边形内

//_selectedRegionPoints是多边形坐标点位集合json字符串bool bl = (bool)_engine.Invoke("calc", new object[] { lng, lat, _selectedRegionPoints });

程序开发完成后发布

C#怎么调用js库

发布后文件夹拷贝到用户的win10系统中可以直接使用,不需要安装.net6环境。我自己的很老的win7 sp1虚拟机上跑不起来,ClearScriptV8.win-x64.dll无法加载成功,暂不知道为什么。

Form1.cs完整代码如下:

当时程序写的急,当然,程序还可以优化,不过没必要,要处理的数据量不大,功能没问题就行。

using Models;using Newtonsoft.Json;using System.Drawing;using System.Text;using System.Text.RegularExpressions;using Microsoft.ClearScript.javascript;using Microsoft.ClearScript.V8;using NPOI.HSSF.UserModel;using NPOI.XSSF.UserModel;using NPOI.SS.UserModel;using System.Reflection;using System.Windows.Forms;using NPOI.Util;namespace 点位{    public partial class Form1 : Form    {        private Regions _regions;        private List<CameraInfo> _cameraList = new List<CameraInfo>();        private V8ScriptEngine _engine = new V8ScriptEngine();        private string _selectedRegionPoints;        public Form1()        {            InitializeComponent();        }        private async void Form1_Load(object sender, EventArgs e)        {            //通过js引擎加载js文件            _engine.AddHostType("Console", typeof(Console));            string fileName = AppDomain.CurrentDomain.BaseDirectory + "turf.v6.5.0.min.js";            string js;            using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))            {                byte[] bArr = new byte[fs.Length];                await fs.ReadAsync(bArr, 0, bArr.Length);                js = ASCIIEncoding.UTF8.GetString(bArr);            }            _engine.Execute(js);            fileName = AppDomain.CurrentDomain.BaseDirectory + "calc.js";            using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))            {                byte[] bArr = new byte[fs.Length];                await fs.ReadAsync(bArr, 0, bArr.Length);                js = ASCIIEncoding.UTF8.GetString(bArr);            }            _engine.Execute(js);            fileName = AppDomain.CurrentDomain.BaseDirectory + "leaflet.mapCorrection.js";            using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))            {                byte[] bArr = new byte[fs.Length];                await fs.ReadAsync(bArr, 0, bArr.Length);                js = ASCIIEncoding.UTF8.GetString(bArr);            }            _engine.Execute(js);            //行政区划下拉列表初始化            fileName = AppDomain.CurrentDomain.BaseDirectory + "安徽.json";            using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))            {                byte[] bArr = new byte[fs.Length];                await fs.ReadAsync(bArr, 0, bArr.Length);                string json = ASCIIEncoding.UTF8.GetString(bArr);                _regions = JsonConvert.DeserializeObject<Regions>(json);            }            List<Records> citys = _regions.RECORDS.ToList().FindAll(a => a.civilcode.Length == 4);            cbxCity.DataSource = citys;            cbxCity.DisplayMember = "civilname";            cbxCity.ValueMember = "civilcode";        }        private void button1_Click(object sender, EventArgs e)        {            openFileDialog1.Title = "选择要处理的excel文件";            openFileDialog1.Filter = "Excel文件(*.xlsx)|*.xlsx";            if (openFileDialog1.ShowDialog() == DialogResult.OK)            {                using (FileStream fs = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read, FileShare.Read))                {                }            }        }        private void cbxCity_SelectedIndexChanged(object sender, EventArgs e)        {            Records record = cbxCity.SelectedItem as Records;            List<Records> citys = _regions.RECORDS.ToList().FindAll(a => a.civilcode.Length > 4 && a.civilcode.Substring(0, 4) == record.civilcode);            citys.Insert(0, new Records() { civilcode = null, civilname = "==请选择==" });            cbxCounty.DataSource = citys;            cbxCounty.DisplayMember = "civilname";            cbxCounty.ValueMember = "civilcode";        }        private void cbxCounty_SelectedIndexChanged(object sender, EventArgs e)        {            Records record = cbxCounty.SelectedItem as Records;            if (record.civilcode == null)            {                record = cbxCity.SelectedItem as Records;            }            Regex regex = new Regex(@"^POLYGON\((\(.*\),?)*\)$");            var mc = regex.Matches(record.polygongeo);            StringBuilder sb = new StringBuilder();            foreach (Match m in mc)            {                string value = m.Groups[1].Value.TrimStart('(').TrimEnd(')');                string[] lnglatArr = value.Split(',');                bool first = true;                if (sb.Length > 0)                {                    sb.Append(",");                }                sb.Append("[[");                foreach (string lnglatStr in lnglatArr)                {                    string[] lnglat = lnglatStr.Trim().Split(' ');                    double lng = Convert.ToDouble(lnglat[0]);                    double lat = Convert.ToDouble(lnglat[1]);                    //坐标纠偏                    dynamic newPoint = _engine.Invoke("correct", new object[] { lng, lat });                    lng = newPoint.lng;                    lat = newPoint.lat;                    if (first)                    {                        first = false;                        sb.AppendFormat($"[{lng}, {lat}]");                    }                    else                    {                        sb.AppendFormat($",[{lng}, {lat}]");                    }                }                sb.Append("]]");            }            _selectedRegionPoints = sb.ToString();        }        private async void openFileDialog1_FileOk(object sender, System.ComponentModel.CancelEventArgs e)        {            await Task.Delay(10);            //读取Excel            _cameraList = new List<CameraInfo>();            using (FileStream fs = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read, FileShare.Read))            {                XSSFWorkbook workbook = new XSSFWorkbook(fs);                ISheet sheet = workbook.GetSheetAt(0);                for (int i = 1; i <= sheet.LastRowNum; i++)                {                    IRow row = sheet.GetRow(i);                    CameraInfo cameraInfo = new CameraInfo();                    cameraInfo.CameraNo = row.GetCell(1).StringCellValue.Trim();                    cameraInfo.City = row.GetCell(2).StringCellValue.Trim();                    cameraInfo.County = row.GetCell(3).StringCellValue.Trim();                    cameraInfo.CameraName = row.GetCell(4).StringCellValue.Trim();                    cameraInfo.Lng = row.GetCell(5).StringCellValue.Trim();                    cameraInfo.Lat = row.GetCell(6).StringCellValue.Trim();                    cameraInfo.CameraFunType = row.GetCell(7).StringCellValue.Trim();                    cameraInfo.Region = row.GetCell(8).StringCellValue.Trim();                    cameraInfo.Type = row.GetCell(9).StringCellValue.Trim();                    cameraInfo.Status = row.GetCell(10).StringCellValue.Trim();                    cameraInfo.Mac = row.GetCell(11).StringCellValue.Trim();                    cameraInfo.Ip = row.GetCell(12).StringCellValue.Trim();                    _cameraList.Add(cameraInfo);                }            }            //过滤数据            _cameraList = _cameraList.FindAll(cameraInfo =>            {                if (!string.IsNullOrWhiteSpace(cameraInfo.Lng) && !string.IsNullOrWhiteSpace(cameraInfo.Lat))                {                    double lng = Convert.ToDouble(cameraInfo.Lng);                    double lat = Convert.ToDouble(cameraInfo.Lat);                    bool bl = (bool)_engine.Invoke("calc", new object[] { lng, lat, _selectedRegionPoints });                    if (bl) //区域内                    {                        return false;                    }                    else //区域外                    {                        return true;                    }                }                else                {                    return false;                }            });            saveFileDialog1.Title = "选择处理结果要保存的位置及文件名";            saveFileDialog1.Filter = "Excel文件(*.xlsx)|*.xlsx";            if (saveFileDialog1.ShowDialog() == DialogResult.OK)            {                if (File.Exists(saveFileDialog1.FileName))                {                    File.Delete(saveFileDialog1.FileName);                }                string template = AppDomain.CurrentDomain.BaseDirectory + "点位模板.xlsx";                XSSFWorkbook workbook;                using (FileStream fs = new FileStream(template, FileMode.Open, FileAccess.Read, FileShare.Read))                {                    workbook = new XSSFWorkbook(fs);                    using (FileStream fs2 = new FileStream(saveFileDialog1.FileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))                    {                        ISheet sheet = workbook.GetSheetAt(0);                        sheet.RemoveRow(sheet.GetRow(1));                        sheet.RemoveRow(sheet.GetRow(2));                        Dictionary<int, ICellStyle> cellStyles = GetCellStyles(sheet);                        int i = 1;                        foreach (CameraInfo cameraInfo in _cameraList)                        {                            IRow row = sheet.CreateRow(i);                            ICell cell1 = row.CreateCell(1, CellType.String);                            ICell cell2 = row.CreateCell(2, CellType.String);                            ICell cell3 = row.CreateCell(3, CellType.String);                            ICell cell4 = row.CreateCell(4, CellType.String);                            ICell cell5 = row.CreateCell(5, CellType.String);                            ICell cell6 = row.CreateCell(6, CellType.String);                            ICell cell7 = row.CreateCell(7, CellType.String);                            ICell cell8 = row.CreateCell(8, CellType.String);                            ICell cell9 = row.CreateCell(9, CellType.String);                            ICell cell10 = row.CreateCell(10, CellType.String);                            ICell cell11 = row.CreateCell(11, CellType.String);                            ICell cell12 = row.CreateCell(12, CellType.String);                            SetCellStyles(row, cellStyles);                            cell1.SetCellValue(cameraInfo.CameraNo);                            cell2.SetCellValue(cameraInfo.City);                            cell3.SetCellValue(cameraInfo.County);                            cell4.SetCellValue(cameraInfo.CameraName);                            cell5.SetCellValue(cameraInfo.Lng);                            cell6.SetCellValue(cameraInfo.Lat);                            cell7.SetCellValue(cameraInfo.CameraFunType);                            cell8.SetCellValue(cameraInfo.Region);                            cell9.SetCellValue(cameraInfo.Type);                            cell10.SetCellValue(cameraInfo.Status);                            cell11.SetCellValue(cameraInfo.Mac);                            cell12.SetCellValue(cameraInfo.Ip);                            i++;                        }                        workbook.Write(fs2);                    }                    MessageBox.Show("完成");                }            }        }        private Dictionary<int, ICellStyle> GetCellStyles(ISheet sheet)        {            var styleRow = sheet.GetRow(5);            Dictionary<int, ICellStyle> result = new Dictionary<int, ICellStyle>();            for (int i = 1; i <= 12; i++)            {                result.Add(i, styleRow.GetCell(i).CellStyle);            }            return result;        }        private void SetCellStyles(IRow row, Dictionary<int, ICellStyle> styles)        {            for (int i = 1; i <= 12; i++)            {                row.GetCell(i).CellStyle = styles[i];            }        }        private void Form1_FormClosing(object sender, FormClosingEventArgs e)        {            _engine.Dispose();        }        private void button2_Click(object sender, EventArgs e)        {            folderBrowserDialog1.Description = "选择模板文件保存位置";            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)            {                string template = AppDomain.CurrentDomain.BaseDirectory + "点位模板.xlsx";                string filePath = Path.Combine(folderBrowserDialog1.SelectedPath, "点位模板.xlsx");                if (File.Exists(filePath))                {                    if (MessageBox.Show("模板文件已存在,是否覆盖?", "提示", MessageBoxButtons.OKCancel) == DialogResult.OK)                    {                        File.Copy(template, filePath, true);                        MessageBox.Show("下载完成");                    }                }                else                {                    File.Copy(template, filePath, true);                    MessageBox.Show("下载完成");                }            }        }    }}

关于“C#怎么调用js库”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注编程网精选频道,小编每天都会为大家更新不同的知识点。

--结束END--

本文标题: C#怎么调用js库

本文链接: https://www.lsjlt.com/news/355799.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • C#怎么调用js库
    这篇文章主要介绍“C#怎么调用js库”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“C#怎么调用js库”文章能帮助大家解决问题。安装ClearScriptClearScript是微软开源的js引擎,支...
    99+
    2023-07-05
  • C#调用js库的方法小结
    目录前言安装ClearScript引入js文件创建V8ScriptEngine对象通过js引擎加载js文件C#调用js方法实现经纬度坐标纠偏C#调用js方法判断经纬度点位是否在多边形...
    99+
    2023-05-14
    C#调用js
  • rust怎么调用c++库
    在Rust中调用C++库,可以使用Rust的FFI(Foreign Function Interface)功能来实现。以下是一般的步...
    99+
    2023-10-26
    rust c++
  • c++ pthread库怎么调用
    要使用pthread库,需要引入头文件`#include `。 下面是一个简单的示例,展示了如何使用pthread库创建和运行一个线...
    99+
    2023-10-26
    c++ pthread
  • golang怎么调用c++库
    要在Golang中调用C++库,你需要使用CGo,它是Golang与C/C++代码交互的一种方式。下面是一个简单的示例,展示了如何调...
    99+
    2023-10-20
    golang c++
  • C++中怎么调用C链接库
    本篇文章给大家分享的是有关C++中怎么调用C链接库,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。C++调用C链接库,其实相对C调用C++。因为C++本来就向下兼容C吧但由于编译...
    99+
    2023-06-17
  • C#调用js库的方法示例代码
    目录前言安装ClearScript引入js文件创建V8ScriptEngine对象通过js引擎加载js文件C#调用js方法实现经纬度坐标纠偏C#调用js方法判断经纬度点位是否在多边形...
    99+
    2023-01-17
    C#调用js库 C# js库 C#调用js
  • java怎么调用c++动态库
    要在Java中调用C++动态库,可以使用JNI(Java Native Interface)技术。以下是通过JNI调用C++动态库的...
    99+
    2023-10-20
    java c++
  • unity怎么调用c++动态库
    要在Unity中调用C++动态库,可以按照以下步骤进行操作:1. 创建C++动态库:首先,使用C++编写你的库,并将其编译为动态库(...
    99+
    2023-09-20
    unity c++
  • 怎么在Java中调用C/C++本地库
    本篇内容介绍了“怎么在Java中调用C/C++本地库”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!编写Java类我们来编写一个Sample1...
    99+
    2023-06-17
  • python调用C库
    编写C库test.c#include <stdio.h> #include <string.h> int strcmpTest(char *a, char *b) { return strcmp(a,...
    99+
    2023-01-31
    python
  • c语言多线程库怎么调用
    在C语言中,可以使用pthread库来进行多线程编程。以下是一个简单的多线程程序示例:```c#include #include #...
    99+
    2023-09-21
    c语言
  • C#怎么调用C++动态库接口函数和回调函数
    本文小编为大家详细介绍“C#怎么调用C++动态库接口函数和回调函数”,内容详细,步骤清晰,细节处理妥当,希望这篇“C#怎么调用C++动态库接口函数和回调函数”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。1. 前言...
    99+
    2023-06-29
  • C#调用动态库
    一、引言 “为什么我们需要掌握互操作技术的呢?” 对于这个问题的解释就是——掌握了.NET平台下的互操作性技术可以帮助我们在.NET中...
    99+
    2024-04-02
  • C++调用动态库和Python调用C++动态库的方法是什么
    这篇文章主要介绍“C++调用动态库和Python调用C++动态库的方法是什么”,在日常操作中,相信很多人在C++调用动态库和Python调用C++动态库的方法是什么问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答...
    99+
    2023-07-05
  • html怎么调用js函数
    这篇文章给大家分享的是有关html怎么调用js函数的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。html调用js函数的方法:1、用控件本身进行调用;2、通过javascript中的时间控件定时执行;3、通过get...
    99+
    2023-06-15
  • js怎么停止setInterval调用
    要停止setInterval调用,可以使用clearInterval函数来清除定时器。 首先,使用setInterval函数创建一个...
    99+
    2023-10-21
    js
  • python怎么调用js文件
    使用python调用js文件的方法:1.新建python项目;2.导入execjs模块;3.使用get_js方法获取js文件;4.使用execjs.compile()方法调用文件;具体步骤如下:首先,打开python,并新建一个python...
    99+
    2024-04-02
  • C#中怎么使用IronPython库调用Python脚本
    在C#中使用IronPython库调用Python脚本的步骤如下: 首先,需要将IronPython库添加到C#项目中。可以通过...
    99+
    2024-03-08
    python C#
  • C++/CLI怎么调用C#
    这篇文章主要讲解了“C++/CLI怎么调用C#”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“C++/CLI怎么调用C#”吧!跨越语言的障碍:C++/CLI 调用 C#当C#项目需要引用C++...
    99+
    2023-06-17
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作