var endindex = 1

本文介绍了一种利用JavaScript实现从网页表格自动导出数据到Excel的方法,并详细展示了如何设置Excel文件的标题、表头及数据填充过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

文章来自 codego.net 请看源代码:
function AutomateExcel() {
try {
//Start Excel and get Application object.
var oXL;
try
{
oXL = new ActiveXObject("Excel.Application");
}
catch(e)
{
alert("无法启动Excel!\n\n如果您确信您的电脑中已经安装了Excel," + "那么请调整IE的安全级别。\n\n具体操作:\n\n" + "工具 → Internet选项 → 安全 → 自定义级别 → 对没有标记为安全的ActiveX进行初始化和脚本运行 → 启用");
return false;
}
//Get a new workbook.
var oWB = oXL.Workbooks.Add();
var oSheet = oWB.ActiveSheet;
var table = $("#GridView1")[0];
var rows = table.rows;
var columns = table.rows(0).cells;
var codes = "";
//设置标题
var name = "第 <%= _CurrentPage %> 页";
oXL.Caption = name;
oSheet.Name = name;
//设置表头
oSheet.Cells(1, 1).Value = "申请单编号";
oSheet.Cells(1, 2).Value = "出货金额";
oSheet.Cells(1, 3).Value = "营销部门";
oSheet.Cells(1, 4).Value = "业务人员";
oSheet.Cells(1, 5).Value = "内部合同号";
oSheet.Cells(1, 6).Value = "客户名称";
oSheet.Cells(1, 7).Value = "币种";
oSheet.Cells(1, 8).Value = "客户船期";
oSheet.Cells(1, 9).Value = "国别";
oSheet.Cells(1, 10).Value = "核销单号";
oSheet.Cells(1, 11).Value = "发票号码";
oSheet.Cells(1,--codego.net--, 12).Value = "报关日期";
//获取当前页申请单编号
for (var i = 2; i <= rows.length; i++) {
codes += "'" + rows(i - 1).cells(0).innerText + "',";
}
codes += "''";
//获取数据并填充数据到EXCEL
$.post("../Handlers/ShippingApplyHandler.ashx",
{ Action: "ExportData", ExportCondition: codes },
function (views) {
if (views != null) {
var beginindex = 1;
var endindex = 1;
for (var i = 0; i < views.length; i++) {
endindex++;
oSheet.Cells(i + 2, 1).Value = views[i].SACode;
oSheet.Cells(i + 2, 2).Value = views[i].AmountSum;
oSheet.Cells(i + 2, 3).Value = views[i].Department;
oSheet.Cells(i + 2, 4).Value = views[i].SalesName;
oSheet.Cells(i + 2, 5).Value = views[i].ContractNo;
oSheet.Cells(i + 2, 6).Value = views[i].CustomerName;
oSheet.Cells(i + 2, 7).Value = views[i].CurrencyCode;
if (views[i].CustomerSchedule != null) {
oSheet.Cells(i + 2, 8).Value = ConvertToJSDate(views[i].CustomerSchedule).Format("yyyy-MM-dd");
}
oSheet.Cells(i + 2, 9).Value = views[i].Country;
oSheet.Cells(i + 2, 10).Value = views[i].VerificationNumber;
oSheet.Cells(i + 2, 11).Value = views[i].InvoiceNumber;
if (views[i].CustomsDate != null) {
oSheet.Cells(i + 2, 12).Value = ConvertToJSDate(views[i].CustomsDate).Format("yyyy-MM-dd");
}
if (i > 0 && views[i - 1].SACode == views[i].SACode) {
oSheet.Range(oSheet.Cells(beginindex, 1), oSheet.Cells(endindex, 1)).Merge();
oSheet.Range(oSheet.Cells(beginindex, 2), oSheet.Cells(endindex, 2)).Merge();
oSheet.Range(oSheet.Cells(beginindex, 3), oSheet.Cells(endindex, 3)).Merge();
oSheet.Range(oSheet.Cells(beginindex, 4), oSheet.Cells(endindex, 4)).Merge();
oSheet.Range(oSheet.Cells(beginindex, 5), oSheet.Cells(endindex, 5)).Merge();
oSheet.Range(oSheet.Cells(beginindex, 6), oSheet.Cells(endindex, 6)).Merge();
oSheet.Range(oSheet.Cells(beginindex, 7), oSheet.Cells(endindex, 7)).Merge();
oSheet.Range(oSheet.Cells(beginindex, 8), oSheet.Cells(endindex, 8)).Merge();
beginindex = endindex;
}
else {
beginindex++;
}
}
}
}, "json");
//设置自动列宽
oSheet.Columns.AutoFit();
//设置excel为可见
oXL.Visible = true;
//将Excel交由用户控制
oXL.UserControl = true;
//禁止提示
oXL.DisplayAlerts = false;
//释放资源
//oXL = null;
//oWB = null;
//oSheet = null;
}
catch (e) {
}
}
using Autodesk.AutoCAD.ApplicationServices; using Autodesk.AutoCAD.Colors; using Autodesk.AutoCAD.DatabaseServices; using Autodesk.AutoCAD.EditorInput; using Autodesk.AutoCAD.Geometry; using Autodesk.AutoCAD.Runtime; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Collections.Concurrent; using System.Reflection; namespace ScaffoldPlugin { public class PluginInitialization : IExtensionApplication { public void Initialize() { Document doc = Application.DocumentManager.MdiActiveDocument; if (doc != null) { doc.Editor.WriteMessage("\n脚手架插件已加载。命令: PS(布置), CS(统计)"); } } public void Terminate() { } } public class ScaffoldCommands { private static readonly double[] BarLengths = { 300, 600, 900, 1200, 1500, 1800 }; private static readonly string BlockDirectory = Path.Combine( Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "ScaffoldBlocks"); private const double Tolerance = 0.001; private const int BatchSize = 5000; private const double SpacingTolerance = 150.0; private const double LineTolerance = 10.0; private const int MaxPoints = 50000; private static Dictionary<string, ObjectId> _cachedBlockDefinitions = new Dictionary<string, ObjectId>(); private const string PoleBlockName = "ScaffoldPole立杆"; private const string HorizontalBarPrefix = "ScaffoldPole横杆"; private const string AxisLayer = "盘扣轴网"; // 轴网专用图层 // 脚手架构件图层 private const string PoleLayer = "Scaffold-Poles"; private const string HorizontalBarLayer = "Scaffold-Bars-X"; private const string VerticalBarLayer = "Scaffold-Bars-Y"; private struct Point3dKey { public readonly long X; public readonly long Y; private const double Scale = 1000.0; public Point3dKey(Point3d pt) { X = (long)(pt.X * Scale); Y = (long)(pt.Y * Scale); } public override bool Equals(object obj) => obj is Point3dKey other && X == other.X && Y == other.Y; public override int GetHashCode() => (int)((X * 397) ^ Y); } [CommandMethod("PlaceScaffold", "PS", CommandFlags.Modal)] public void PlaceScaffold() { Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; try { if (!Directory.Exists(BlockDirectory)) { Directory.CreateDirectory(BlockDirectory); ShowErrorDialog($"块目录已创建: {BlockDirectory}\n请添加块文件后重新运行命令"); return; } // 创建所需图层 CreateLayerIfNotExists(db, PoleLayer, 7); // 白色 CreateLayerIfNotExists(db, HorizontalBarLayer, 1); // 红色 CreateLayerIfNotExists(db, VerticalBarLayer, 5); // 蓝色 // 选择轴网线(只选择"盘扣轴网"图层) var axisLineIds = SelectAxisLines(ed); if (axisLineIds == null || axisLineIds.Count == 0) { ShowErrorDialog("未选择轴网线或操作已取消!"); return; } List<Line> axisLines = GetAxisLinesFromIds(db, axisLineIds); if (axisLines.Count == 0) { ShowErrorDialog("未找到轴网线!"); return; } ed.WriteMessage("\n正在计算交点..."); List<Point3d> points = GetIntersectionPoints(axisLines); if (points.Count == 0) { ShowErrorDialog("未找到有效交点!"); return; } ed.WriteMessage($"\n找到 {points.Count} 个交点"); if (points.Count > MaxPoints) { ShowErrorDialog($"交点数量超过上限 ({MaxPoints})!\n请缩小布置范围或简化轴网"); return; } ed.WriteMessage("\n正在加载块定义..."); if (!LoadBlockDefinitions(db, ed)) return; ed.WriteMessage("\n开始清理重叠区域的现有脚手架..."); CleanOverlappingScaffold(db, points, ed); ed.WriteMessage("\n开始布置立杆..."); int poleCount = PlacePoles(db, points, ed); ed.WriteMessage($"\n已布置 {poleCount} 根立杆"); ed.WriteMessage("\n开始布置横杆..."); int barCount = PlaceBars(db, points, axisLines, ed); ed.WriteMessage($"\n已布置 {barCount} 根横杆"); if (poleCount == 0 && barCount == 0) { ShowErrorDialog("脚手架布置失败,未布置任何构件!"); } else { ed.WriteMessage($"\n成功布置 {poleCount}根立杆和{barCount}根横杆!"); } } catch (System.Exception ex) { ShowErrorDialog($"发生错误: {ex.Message}\n详细请查看命令行日志"); ed.WriteMessage($"\n错误: {ex.Message}\n{ex.StackTrace}"); } } [CommandMethod("CountScaffoldBlocks", "CS", CommandFlags.Modal)] public void CountScaffoldBlocks() { Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; try { TypedValue[] filterValues = { new TypedValue((int)DxfCode.Start, "INSERT"), new TypedValue((int)DxfCode.Operator, "<or"), new TypedValue((int)DxfCode.BlockName, PoleBlockName), new TypedValue((int)DxfCode.BlockName, VerticalBarPrefix + "*"), new TypedValue((int)DxfCode.BlockName, HorizontalBarPrefix + "*"), new TypedValue((int)DxfCode.Operator, "or>") }; SelectionFilter filter = new SelectionFilter(filterValues); PromptSelectionResult selResult = ed.GetSelection(new PromptSelectionOptions(), filter); if (selResult.Status != PromptStatus.OK) return; Dictionary<(string type, int length), int> blockCounts = new Dictionary<(string, int), int>(); using (Transaction trans = db.TransactionManager.StartTransaction()) { foreach (SelectedObject selObj in selResult.Value) { BlockReference blockRef = trans.GetObject(selObj.ObjectId, OpenMode.ForRead) as BlockReference; if (blockRef == null) continue; BlockTableRecord btr = trans.GetObject(blockRef.BlockTableRecord, OpenMode.ForRead) as BlockTableRecord; string blockName = btr.Name; string blockType = ""; int barLength = 0; if (blockName == PoleBlockName) blockType = "立杆"; else if (blockName.StartsWith(VerticalBarPrefix)) { blockType = "横杆"; barLength = ExtractBarLength(blockName, VerticalBarPrefix); } else if (blockName.StartsWith(HorizontalBarPrefix)) { blockType = "横杆"; barLength = ExtractBarLength(blockName, HorizontalBarPrefix); } else continue; var key = (type: blockType, length: barLength); blockCounts[key] = blockCounts.ContainsKey(key) ? blockCounts[key] + 1 : 1; } trans.Commit(); } CreateStatisticsTable(db, ed, blockCounts); } catch (System.Exception ex) { ed.WriteMessage($"\n统计错误: {ex.Message}"); } } private int ExtractBarLength(string blockName, string prefix) { try { string lengthPart = blockName.Substring(prefix.Length); if (lengthPart.EndsWith("mm")) lengthPart = lengthPart.Substring(0, lengthPart.Length - 2); if (int.TryParse(lengthPart, out int length)) return length; } catch { } return 0; } private void CreateStatisticsTable(Database db, Editor ed, Dictionary<(string type, int length), int> blockCounts) { if (blockCounts.Count == 0) { ed.WriteMessage("\n未找到可统计的脚手架块!"); return; } PromptPointResult ppr = ed.GetPoint("\n指定表格插入点: "); if (ppr.Status != PromptStatus.OK) return; using (Transaction trans = db.TransactionManager.StartTransaction()) { BlockTableRecord modelSpace = trans.GetObject( SymbolUtilityServices.GetBlockModelSpaceId(db), OpenMode.ForWrite) as BlockTableRecord; Table table = new Table(); table.SetDatabaseDefaults(); table.Position = ppr.Value; table.SetSize(blockCounts.Count + 4, 4); for (int i = 0; i < 4; i++) table.Columns[i].Width = i == 0 ? 15 : 25; table.MergeCells(CellRange.Create(table, 0, 0, 0, 3)); table.Cells[0, 0].TextString = "盘扣平面布置数量统计表"; table.Cells[0, 0].Alignment = CellAlignment.MiddleCenter; table.Cells[1, 0].TextString = "序号"; table.Cells[1, 1].TextString = "杆件名称"; table.Cells[1, 2].TextString = "杆件长mm"; table.Cells[1, 3].TextString = "数量统计/根"; int rowIndex = 2; int seqNo = 1; foreach (var kvp in blockCounts) { table.Cells[rowIndex, 0].TextString = seqNo.ToString(); table.Cells[rowIndex, 0].Alignment = CellAlignment.MiddleCenter; table.Cells[rowIndex, 1].TextString = kvp.Key.type; table.Cells[rowIndex, 1].Alignment = CellAlignment.MiddleLeft; table.Cells[rowIndex, 2].TextString = kvp.Key.type == "立杆" ? "" : kvp.Key.length.ToString(); table.Cells[rowIndex, 2].Alignment = CellAlignment.MiddleCenter; table.Cells[rowIndex, 3].TextString = kvp.Value.ToString(); table.Cells[rowIndex, 3].Alignment = CellAlignment.MiddleCenter; rowIndex++; seqNo++; } rowIndex++; table.MergeCells(CellRange.Create(table, rowIndex, 0, rowIndex, 2)); table.Cells[rowIndex, 0].TextString = "总计"; table.Cells[rowIndex, 0].Alignment = CellAlignment.MiddleRight; table.Cells[rowIndex, 3].TextString = blockCounts.Values.Sum().ToString(); modelSpace.AppendEntity(table); trans.AddNewlyCreatedDBObject(table, true); trans.Commit(); } ed.WriteMessage($"\n已生成统计表格,总计 {blockCounts.Values.Sum()} 根。"); } private List<ObjectId> SelectAxisLines(Editor ed) { var lineIds = new List<ObjectId>(); // 只选择"盘扣轴网"图层的线段 var filter = new SelectionFilter(new[] { new TypedValue(0, "LINE"), new TypedValue(8, AxisLayer) // 图层过滤 }); PromptSelectionResult selection = ed.GetSelection(filter); if (selection.Status != PromptStatus.OK) return lineIds; using (var trans = ed.Document.TransactionManager.StartTransaction()) { foreach (SelectedObject selectedObject in selection.Value) { if (selectedObject != null) lineIds.Add(selectedObject.ObjectId); } trans.Commit(); } return lineIds; } private List<Line> GetAxisLinesFromIds(Database db, List<ObjectId> axisLineIds) { List<Line> lines = new List<Line>(); using (Transaction trans = db.TransactionManager.StartTransaction()) { foreach (ObjectId id in axisLineIds) { if (id.IsValid && !id.IsErased) { Line line = trans.GetObject(id, OpenMode.ForRead) as Line; if (line != null) lines.Add(line); } } trans.Commit(); } return lines; } private List<Point3d> GetIntersectionPoints(List<Line> axisLines) { var points = new List<Point3d>(); var pointSet = new HashSet<Point3dKey>(); // 优化:先按方向分组 var horizontalLines = new List<Line>(); var verticalLines = new List<Line>(); foreach (var line in axisLines) { if (Math.Abs(line.StartPoint.Y - line.EndPoint.Y) < Tolerance) horizontalLines.Add(line); else if (Math.Abs(line.StartPoint.X - line.EndPoint.X) < Tolerance) verticalLines.Add(line); } // 并行计算交点 var pointsLock = new object(); System.Threading.Tasks.Parallel.ForEach(horizontalLines, horizontalLine => { foreach (var verticalLine in verticalLines) { Point3d? inters = GetIntersection(horizontalLine, verticalLine); if (inters != null) { var key = new Point3dKey(inters.Value); lock (pointsLock) { if (!pointSet.Contains(key)) { points.Add(inters.Value); pointSet.Add(key); } } } } }); return points; } private Point3d? GetIntersection(Line line1, Line line2) { Point3dCollection points = new Point3dCollection(); line1.IntersectWith(line2, Intersect.OnBothOperands, points, IntPtr.Zero, IntPtr.Zero); return points.Count > 0 ? (Point3d?)points[0] : null; } private bool LoadBlockDefinitions(Database db, Editor ed) { if (!Directory.Exists(BlockDirectory)) { ed.WriteMessage($"\n错误: 块文件目录不存在 {BlockDirectory}"); return false; } using (var trans = db.TransactionManager.StartTransaction()) { BlockTable blockTable = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; foreach (var file in Directory.GetFiles(BlockDirectory, "*.dwg")) { string blockName = Path.GetFileNameWithoutExtension(file); if (_cachedBlockDefinitions.ContainsKey(blockName)) continue; try { using (var sourceDb = new Database(false, true)) { sourceDb.ReadDwgFile(file, FileShare.Read, true, null); ObjectId blockId = db.Insert(blockName, sourceDb, true); _cachedBlockDefinitions[blockName] = blockId; } } catch (System.Exception ex) { ed.WriteMessage($"\n加载块错误: {file} - {ex.Message}"); } } trans.Commit(); } return true; } private void CleanOverlappingScaffold(Database db, List<Point3d> newPoints, Editor ed) { var pointSet = new HashSet<Point3dKey>(newPoints.Select(p => new Point3dKey(p))); using (var trans = db.TransactionManager.StartTransaction()) { BlockTableRecord modelSpace = trans.GetObject( SymbolUtilityServices.GetBlockModelSpaceId(db), OpenMode.ForWrite) as BlockTableRecord; List<ObjectId> toErase = new List<ObjectId>(); foreach (ObjectId id in modelSpace) { BlockReference blockRef = trans.GetObject(id, OpenMode.ForRead) as BlockReference; if (blockRef == null) continue; BlockTableRecord btr = trans.GetObject(blockRef.BlockTableRecord, OpenMode.ForRead) as BlockTableRecord; string blockName = btr.Name; // 只清理脚手架图层上的对象 if (blockRef.Layer == PoleLayer || blockRef.Layer == HorizontalBarLayer || blockRef.Layer == VerticalBarLayer) { var blockKey = new Point3dKey(blockRef.Position); if (pointSet.Contains(blockKey)) { toErase.Add(id); } } } foreach (ObjectId id in toErase) { Entity entity = trans.GetObject(id, OpenMode.ForWrite) as Entity; entity?.Erase(); } trans.Commit(); ed.WriteMessage($"\n清理了 {toErase.Count} 个重叠的脚手架对象"); } } private int PlacePoles(Database db, List<Point3d> points, Editor ed) { int count = 0; ObjectId poleBlockId = ObjectId.Null; using (var trans = db.TransactionManager.StartTransaction()) { BlockTable blockTable = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; if (blockTable.Has(PoleBlockName)) poleBlockId = blockTable[PoleBlockName]; trans.Commit(); } if (poleBlockId == ObjectId.Null) { ed.WriteMessage($"\n错误: 未找到立杆块定义: {PoleBlockName}"); return 0; } int batchCount = (int)Math.Ceiling((double)points.Count / BatchSize); for (int batchIndex = 0; batchIndex < batchCount; batchIndex++) { using (var trans = db.TransactionManager.StartTransaction()) { BlockTableRecord modelSpace = trans.GetObject( SymbolUtilityServices.GetBlockModelSpaceId(db), OpenMode.ForWrite) as BlockTableRecord; int startIndex = batchIndex * BatchSize; int endIndex = Math.Min(startIndex + BatchSize, points.Count); for (int i = startIndex; i < endIndex; i++) { BlockReference blockRef = new BlockReference(points[i], poleBlockId); blockRef.Layer = PoleLayer; modelSpace.AppendEntity(blockRef); trans.AddNewlyCreatedDBObject(blockRef, true); count++; } trans.Commit(); } } return count; } private int PlaceBars(Database db, List<Point3d> points, List<Line> axisLines, Editor ed) { int count = 0; var barsToPlace = new List<Tuple<Point3d, ObjectId, string>>(); var placedSegments = new HashSet<string>(); var pointSet = new HashSet<Point3dKey>(points.Select(p => new Point3dKey(p))); // 1. 横杆布置 var horizontalPoints = points .GroupBy(p => Math.Round(p.Y / Tolerance) * Tolerance) .Where(g => g.Count() >= 2) .ToList(); foreach (var group in horizontalPoints) { var sortedPoints = group.OrderBy(p => p.X).ToList(); for (int i = 0; i < sortedPoints.Count - 1; i++) { Point3d p1 = sortedPoints[i]; Point3d p2 = sortedPoints[i + 1]; double distance = p1.DistanceTo(p2); if (!IsValidSpacing(distance)) continue; string segKey = $"{Math.Round(p1.X,4)}_{Math.Round(p1.Y,4)}_{Math.Round(p2.X,4)}_{Math.Round(p2.Y,4)}"; if (placedSegments.Contains(segKey)) continue; placedSegments.Add(segKey); ObjectId barBlockId = FindClosestBlock(distance, HorizontalBarPrefix); if (barBlockId == ObjectId.Null) continue; Point3d midPoint = new Point3d( (p1.X + p2.X) / 2.0, (p1.Y + p2.Y) / 2.0, 0); barsToPlace.Add(Tuple.Create(midPoint, barBlockId, HorizontalBarLayer)); count++; } } // 2. 横杆布置 var verticalPoints = points .GroupBy(p => Math.Round(p.X / Tolerance) * Tolerance) .Where(g => g.Count() >= 2) .ToList(); foreach (var group in verticalPoints) { var sortedPoints = group.OrderBy(p => p.Y).ToList(); for (int i = 0; i < sortedPoints.Count - 1; i++) { Point3d p1 = sortedPoints[i]; Point3d p2 = sortedPoints[i + 1]; double distance = p1.DistanceTo(p2); if (!IsValidSpacing(distance)) continue; string segKey = $"{Math.Round(p1.X,4)}_{Math.Round(p1.Y,4)}_{Math.Round(p2.X,4)}_{Math.Round(p2.Y,4)}"; if (placedSegments.Contains(segKey)) continue; placedSegments.Add(segKey); ObjectId barBlockId = FindClosestBlock(distance, VerticalBarPrefix); if (barBlockId == ObjectId.Null) continue; Point3d midPoint = new Point3d( (p1.X + p2.X) / 2.0, (p1.Y + p2.Y) / 2.0, 0); barsToPlace.Add(Tuple.Create(midPoint, barBlockId, VerticalBarLayer)); count++; } } // 批量放置横杆 int batchCount = (int)Math.Ceiling((double)barsToPlace.Count / BatchSize); for (int batchIndex = 0; batchIndex < batchCount; batchIndex++) { using (var trans = db.TransactionManager.StartTransaction()) { BlockTableRecord modelSpace = trans.GetObject( SymbolUtilityServices.GetBlockModelSpaceId(db), OpenMode.ForWrite) as BlockTableRecord; int startIndex = batchIndex * BatchSize; int endIndex = Math.Min(startIndex + BatchSize, barsToPlace.Count); for (int i = startIndex; i < endIndex; i++) { var bar = barsToPlace[i]; BlockReference blockRef = new BlockReference(bar.Item1, bar.Item2); blockRef.Layer = bar.Item3; modelSpace.AppendEntity(blockRef); trans.AddNewlyCreatedDBObject(blockRef, true); } trans.Commit(); } } return count; } private ObjectId FindClosestBlock(double distance, string prefix) { double minDiff = double.MaxValue; ObjectId closestBlock = ObjectId.Null; foreach (var kvp in _cachedBlockDefinitions) { if (!kvp.Key.StartsWith(prefix)) continue; string lengthStr = kvp.Key.Replace(prefix, "").Replace("mm", ""); if (!double.TryParse(lengthStr, out double length)) continue; double diff = Math.Abs(length - distance); if (diff < minDiff && diff <= SpacingTolerance) { minDiff = diff; closestBlock = kvp.Value; } } return closestBlock; } private bool IsValidSpacing(double distance) { foreach (double spacing in BarLengths) { if (Math.Abs(distance - spacing) <= SpacingTolerance) return true; } return false; } private void CreateLayerIfNotExists(Database db, string layerName, short colorIndex) { using (Transaction tr = db.TransactionManager.StartTransaction()) { LayerTable lt = tr.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable; if (!lt.Has(layerName)) { lt.UpgradeOpen(); LayerTableRecord ltr = new LayerTableRecord { Name = layerName, Color = Color.FromColorIndex(ColorMethod.ByAci, colorIndex) }; lt.Add(ltr); tr.AddNewlyCreatedDBObject(ltr, true); tr.Commit(); } } } } // 点比较器(用于Distinct) public class Point3dEqualityComparer : IEqualityComparer<Point3d> { private readonly double _tolerance; public Point3dEqualityComparer(double tolerance) { _tolerance = tolerance; } public bool Equals(Point3d p1, Point3d p2) { return Math.Abs(p1.X - p2.X) < _tolerance && Math.Abs(p1.Y - p2.Y) < _tolerance && Math.Abs(p1.Z - p2.Z) < _tolerance; } public int GetHashCode(Point3d p) { return p.X.GetHashCode() ^ p.Y.GetHashCode() ^ p.Z.GetHashCode(); } } } 根据以上代码修改添加自动识别斜正交网格布置横杆
07-07
winform中以下代码可以帮我整合成一个类供给主程序调用。目前只支持5个串口和5个modubusRTU主站的通讯读写后续可能还要增加多个这种设备。using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.IO.Ports; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using EasyModbus; using static System.Windows.Forms.VisualStyles.VisualStyleElement.Button; namespace 多个串口类 { public partial class Form1 : Form { static ModbusClient modbusrtu0 = new ModbusClient("COM1"); static ModbusClient modbusrtu1 = new ModbusClient("COM2"); static ModbusClient modbusrtu2 = new ModbusClient("COM3"); static ModbusClient modbusrtu3 = new ModbusClient("COM4"); static ModbusClient modbusrtu4 = new ModbusClient("COM5"); static ModbusClient modbusrtu5 = new ModbusClient("COM6"); static ModbusClient modbusrtu6 = new ModbusClient("COM7"); static ModbusClient modbusrtu7 = new ModbusClient("COM8"); static ModbusClient modbusrtu8 = new ModbusClient("COM9"); static ModbusClient modbusrtu9 = new ModbusClient("COM10"); private Thread modbusThread0; private Thread modbusThread1; private Thread modbusThread2; private Thread modbusThread3; private Thread modbusThread4; private Thread modbusThread5; private Thread modbusThread6; private Thread modbusThread7; private Thread modbusThread8; private Thread modbusThread9; int[] modbusRtuInt_0=new int[1000]; int[] modbusRtuInt_1 = new int[1000]; int[] modbusRtuInt_2 = new int[1000]; int[] modbusRtuInt_3 = new int[1000]; int[] modbusRtuInt_4 = new int[1000]; SerialPort sPort_0; SerialPort sPort_1; SerialPort sPort_2; SerialPort sPort_3; SerialPort sPort_4; SerialPort sPort_5; SerialPort sPort_6; SerialPort sPort_7; SerialPort sPort_8; SerialPort sPort_9; private StringBuilder receivedDataBuffer0 = new StringBuilder(); private StringBuilder receivedDataBuffer1 = new StringBuilder(); private StringBuilder receivedDataBuffer2 = new StringBuilder(); private StringBuilder receivedDataBuffer3 = new StringBuilder(); private StringBuilder receivedDataBuffer4 = new StringBuilder(); string sPort0_ReceiveStr = ""; string sPort1_ReceiveStr = ""; string sPort2_ReceiveStr = ""; string sPort3_ReceiveStr = ""; string sPort4_ReceiveStr = ""; // 获取执行程序的根目录路径 public static string rootPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory); public Form1() { InitializeComponent(); } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { //新建任务流程csv文件 string TaskCSVname = rootPath + "\\" + "串口数据列表.csv"; if (!File.Exists(TaskCSVname)) { try { using (FileStream fs = File.Create(TaskCSVname)) { } } catch (Exception ex) { System.Windows.Forms.MessageBox.Show($"创建用户程序 任务流程csv文件时发生错误: {ex.Message}"); } } if (File.Exists(TaskCSVname)) { SaveDataGridViewToCsv(TaskCSVname, dataGridView); } } private void Form1_Load(object sender, EventArgs e) { DataGridViewComboBoxColumn comboBoxColumn_COM = dataGridView.Columns[2] as DataGridViewComboBoxColumn; DataGridViewComboBoxColumn comboBoxColumn_Baudrate = dataGridView.Columns[3] as DataGridViewComboBoxColumn; DataGridViewComboBoxColumn comboBoxColumn_Databits = dataGridView.Columns[4] as DataGridViewComboBoxColumn; DataGridViewComboBoxColumn comboBoxColumn_Stopbit = dataGridView.Columns[5] as DataGridViewComboBoxColumn; DataGridViewComboBoxColumn comboBoxColumn_Checkbit = dataGridView.Columns[6] as DataGridViewComboBoxColumn; DataGridViewComboBoxColumn comboBoxColumn_End = dataGridView.Columns[7] as DataGridViewComboBoxColumn; DataGridViewComboBoxColumn comboBoxColumn_Agreement = dataGridView.Columns[8] as DataGridViewComboBoxColumn; string[] portNames = SerialPort.GetPortNames(); // 获取所有可用串口的名字[^3] string[] Baudrate_strs = { "9600", "19200", "38400", "56000", "115200" }; string[] Databits_strs = { "7", "8" }; string[] Stopbit_strs = { "1","2" }; string[] Checkbit_strs = { "无校验","奇校验", "偶校验" }; string[] End_strs = { "无", "/r", "/n", "/r/n" }; string[] Agreement_strs = { "通用", "Modbus_RTU" }; foreach (string portName in portNames) { comboBoxColumn_COM.Items.Add(portName); } foreach (string Baudrate_str in Baudrate_strs) { comboBoxColumn_Baudrate.Items.Add(Baudrate_str); } foreach (string Databits_str in Databits_strs) { comboBoxColumn_Databits.Items.Add(Databits_str); } foreach (string Stopbit_str in Stopbit_strs) { comboBoxColumn_Stopbit.Items.Add(Stopbit_str); } foreach (string Checkbit_str in Checkbit_strs) { comboBoxColumn_Checkbit.Items.Add(Checkbit_str); } foreach (string End_str in End_strs) { comboBoxColumn_End.Items.Add(End_str); } foreach (string Agreement_str in Agreement_strs) { comboBoxColumn_Agreement.Items.Add(Agreement_str); } string UserProTaskCSVname = rootPath + "\\" + "串口数据列表.csv"; //读取用户程序 任务流程csv文件 if (File.Exists(UserProTaskCSVname)) { LoadCsvToFixedDataGridView(UserProTaskCSVname, dataGridView); } else { } } private void dataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e) { string open_state = ""; string close_state = ""; // 获取点击的行索引和列索引 int rowIndex = e.RowIndex; int columnIndex = e.ColumnIndex; // 判断是否为按钮列 if (dataGridView.Columns[columnIndex] is DataGridViewButtonColumn && rowIndex >= 0) { string dgvPortName_str = dataGridView.Rows[rowIndex].Cells[2].FormattedValue.ToString(); string dgvBaudrate_str= dataGridView.Rows[rowIndex].Cells[3].FormattedValue.ToString(); string dgvDatabits_str = dataGridView.Rows[rowIndex].Cells[4].FormattedValue.ToString(); string dgvStopbit_str = dataGridView.Rows[rowIndex].Cells[5].FormattedValue.ToString(); string dgvCheckbit_str = dataGridView.Rows[rowIndex].Cells[6].FormattedValue.ToString(); string dgvAgreement_str= dataGridView.Rows[rowIndex].Cells[8].FormattedValue.ToString(); //打开连接按钮 if (columnIndex == 10) { if (rowIndex == 0) { if (dgvAgreement_str == "通用") { sPort_0 = new SerialPort(); sPort_open(sPort_0, dgvPortName_str, dgvBaudrate_str, dgvDatabits_str, dgvStopbit_str, dgvCheckbit_str, rowIndex, out open_state); } else if (dgvAgreement_str == "Modbus_RTU") { try { modbusrtu0 = new ModbusClient(dgvPortName_str); modbusrtu0.UnitIdentifier = 1; modbusrtu0.Baudrate = int.Parse(dgvBaudrate_str); // 获取选择的波特率 modbusrtu0.StopBits = StopBits.One; modbusrtu0.ConnectionTimeout = 500; //校验位 if (dgvCheckbit_str == "无") { modbusrtu0.Parity = Parity.None; } else if (dgvCheckbit_str == "奇校验") { modbusrtu0.Parity = Parity.Odd; } else if (dgvCheckbit_str == "偶校验") { modbusrtu0.Parity = Parity.Even; } // 尝试连接 modbusrtu0.Connect(); if (modbusrtu0.Connected) { open_state = "OK"; } } catch { open_state = "NG"; } if (open_state == "OK") { modbusThread0 = new Thread(ContBackgWork_modbusrtu0); modbusThread0.IsBackground = true; modbusThread0.Start(); } } if (open_state == "OK") { dataGridView.Rows[rowIndex].Cells[9].Value = true; } } else if (rowIndex == 1) { if (dgvAgreement_str == "通用") { sPort_1 = new SerialPort(); sPort_open(sPort_1, dgvPortName_str, dgvBaudrate_str, dgvDatabits_str, dgvStopbit_str, dgvCheckbit_str, rowIndex, out open_state); } else if (dgvAgreement_str == "Modbus_RTU") { try { modbusrtu1 = new ModbusClient(dgvPortName_str); modbusrtu1.UnitIdentifier = 1; modbusrtu1.Baudrate = int.Parse(dgvBaudrate_str); // 获取选择的波特率 modbusrtu1.StopBits = StopBits.One; modbusrtu1.ConnectionTimeout = 500; //校验位 if (dgvCheckbit_str == "无") { modbusrtu1.Parity = Parity.None; } else if (dgvCheckbit_str == "奇校验") { modbusrtu1.Parity = Parity.Odd; } else if (dgvCheckbit_str == "偶校验") { modbusrtu1.Parity = Parity.Even; } // 尝试连接 modbusrtu1.Connect(); if (modbusrtu1.Connected) { open_state = "OK"; } } catch { open_state = "NG"; } if (open_state == "OK") { modbusThread1 = new Thread(ContBackgWork_modbusrtu1); modbusThread1.IsBackground = true; modbusThread1.Start(); } } if (open_state == "OK") { dataGridView.Rows[rowIndex].Cells[9].Value = true; } } else if (rowIndex == 2) { if (dgvAgreement_str == "通用") { sPort_2 = new SerialPort(); sPort_open(sPort_2, dgvPortName_str, dgvBaudrate_str, dgvDatabits_str, dgvStopbit_str, dgvCheckbit_str, rowIndex, out open_state); } else if (dgvAgreement_str == "Modbus_RTU") { try { modbusrtu2 = new ModbusClient(dgvPortName_str); modbusrtu2.UnitIdentifier = 1; modbusrtu2.Baudrate = int.Parse(dgvBaudrate_str); // 获取选择的波特率 modbusrtu2.StopBits = StopBits.One; modbusrtu2.ConnectionTimeout = 500; //校验位 if (dgvCheckbit_str == "无") { modbusrtu2.Parity = Parity.None; } else if (dgvCheckbit_str == "奇校验") { modbusrtu2.Parity = Parity.Odd; } else if (dgvCheckbit_str == "偶校验") { modbusrtu2.Parity = Parity.Even; } // 尝试连接 modbusrtu2.Connect(); if (modbusrtu2.Connected) { open_state = "OK"; } } catch { open_state = "NG"; } if (open_state == "OK") { modbusThread2 = new Thread(ContBackgWork_modbusrtu2); modbusThread2.IsBackground = true; modbusThread2.Start(); } } if (open_state == "OK") { dataGridView.Rows[rowIndex].Cells[9].Value = true; } } else if (rowIndex == 3) { if (dgvAgreement_str == "通用") { sPort_3 = new SerialPort(); sPort_open(sPort_3, dgvPortName_str, dgvBaudrate_str, dgvDatabits_str, dgvStopbit_str, dgvCheckbit_str, rowIndex, out open_state); } else if (dgvAgreement_str == "Modbus_RTU") { try { modbusrtu3 = new ModbusClient(dgvPortName_str); modbusrtu3.UnitIdentifier = 1; modbusrtu3.Baudrate = int.Parse(dgvBaudrate_str); // 获取选择的波特率 modbusrtu3.StopBits = StopBits.One; modbusrtu3.ConnectionTimeout = 500; //校验位 if (dgvCheckbit_str == "无") { modbusrtu3.Parity = Parity.None; } else if (dgvCheckbit_str == "奇校验") { modbusrtu3.Parity = Parity.Odd; } else if (dgvCheckbit_str == "偶校验") { modbusrtu3.Parity = Parity.Even; } // 尝试连接 modbusrtu3.Connect(); if (modbusrtu3.Connected) { open_state = "OK"; } } catch { open_state = "NG"; } if (open_state == "OK") { modbusThread3 = new Thread(ContBackgWork_modbusrtu3); modbusThread3.IsBackground = true; modbusThread3.Start(); } } if (open_state == "OK") { dataGridView.Rows[rowIndex].Cells[9].Value = true; } } else if (rowIndex == 4) { if (dgvAgreement_str == "通用") { sPort_4 = new SerialPort(); sPort_open(sPort_4, dgvPortName_str, dgvBaudrate_str, dgvDatabits_str, dgvStopbit_str, dgvCheckbit_str, rowIndex, out open_state); } else if (dgvAgreement_str == "Modbus_RTU") { try { modbusrtu4 = new ModbusClient(dgvPortName_str); modbusrtu4.UnitIdentifier = 1; modbusrtu4.Baudrate = int.Parse(dgvBaudrate_str); // 获取选择的波特率 modbusrtu4.StopBits = StopBits.One; modbusrtu4.ConnectionTimeout = 500; //校验位 if (dgvCheckbit_str == "无") { modbusrtu4.Parity = Parity.None; } else if (dgvCheckbit_str == "奇校验") { modbusrtu4.Parity = Parity.Odd; } else if (dgvCheckbit_str == "偶校验") { modbusrtu4.Parity = Parity.Even; } // 尝试连接 modbusrtu4.Connect(); if (modbusrtu4.Connected) { open_state = "OK"; } } catch { open_state = "NG"; } if (open_state == "OK") { modbusThread4 = new Thread(ContBackgWork_modbusrtu4); modbusThread4.IsBackground = true; modbusThread4.Start(); } } if (open_state == "OK") { dataGridView.Rows[rowIndex].Cells[9].Value = true; } } } //关闭连接按钮 else if (columnIndex == 11) { if (rowIndex == 0) { if (dgvAgreement_str == "通用") { sPort_close(sPort_0, out close_state); } else if(dgvAgreement_str == "Modbus_RTU") { modbusThread0.Abort(); modbusrtu0.Disconnect(); close_state= "OK"; } if (close_state == "OK") { dataGridView.Rows[rowIndex].Cells[9].Value = false; } } else if (rowIndex == 1) { if (dgvAgreement_str == "通用") { sPort_close(sPort_1, out close_state); } else if (dgvAgreement_str == "Modbus_RTU") { modbusThread1.Abort(); modbusrtu1.Disconnect(); close_state = "OK"; } if (close_state == "OK") { dataGridView.Rows[rowIndex].Cells[9].Value = false; } } else if (rowIndex == 2) { if (dgvAgreement_str == "通用") { sPort_close(sPort_2, out close_state); } else if (dgvAgreement_str == "Modbus_RTU") { modbusThread2.Abort(); modbusrtu2.Disconnect(); close_state = "OK"; } if (close_state == "OK") { dataGridView.Rows[rowIndex].Cells[9].Value = false; } } else if (rowIndex == 3) { if (dgvAgreement_str == "通用") { sPort_close(sPort_3, out close_state); } else if (dgvAgreement_str == "Modbus_RTU") { modbusThread3.Abort(); modbusrtu3.Disconnect(); close_state = "OK"; } if (close_state == "OK") { dataGridView.Rows[rowIndex].Cells[9].Value = false; } } else if (rowIndex == 4) { if (dgvAgreement_str == "通用") { sPort_close(sPort_4, out close_state); } else if (dgvAgreement_str == "Modbus_RTU") { modbusThread4.Abort(); modbusrtu4.Disconnect(); close_state = "OK"; } if (close_state == "OK") { dataGridView.Rows[rowIndex].Cells[9].Value = false; } } } } } private void sPort_open(SerialPort sPort, string PortName, string Baudrate, string Databits, string Stopbit, string Checkbit,int Row,out string Result) { Result = ""; if (sPort.IsOpen == false) { try { sPort.PortName = PortName; // 获取选择的串口端口 sPort.BaudRate = int.Parse(Baudrate); // 获取选择的波特率 sPort.DataBits = int.Parse(Databits); // 数据位 //停止位 if (Stopbit == "1") { sPort.StopBits = StopBits.One; } else if (Stopbit == "2") { sPort.StopBits = StopBits.Two; } //校验位 if (Checkbit == "无校验") { sPort.Parity = Parity.None; } else if (Checkbit == "奇校验") { sPort.Parity = Parity.Odd; } else if (Checkbit == "偶校验") { sPort.Parity = Parity.Even; } // 打开串口 sPort.Open(); if (sPort.IsOpen) { if (Row == 0) { sPort.DataReceived += sPort0_DataReceived; } else if (Row == 1) { sPort.DataReceived += sPort1_DataReceived; } else if (Row == 2) { sPort.DataReceived += sPort2_DataReceived; } else if (Row == 3) { sPort.DataReceived += sPort3_DataReceived; } else if (Row == 4) { sPort.DataReceived += sPort4_DataReceived; } Result = "OK"; } } catch { Result = "NG"; } } else { Result = "opened"; } } private void sPort_close(SerialPort sPort, out string Result) { if (sPort != null && sPort.IsOpen) { sPort.Close(); Result = "OK"; } else { Result = "closed"; } } private void button1_Click(object sender, EventArgs e) { if (comboBox1.SelectedIndex == 0) { sPort_send(sPort_0, textBox1.Text); } else if (comboBox1.SelectedIndex == 1) { sPort_send(sPort_1, textBox1.Text); } else if (comboBox1.SelectedIndex == 2) { sPort_send(sPort_2, textBox1.Text); } } private void sPort_send(SerialPort sPort,string sendData) { if (sPort != null && sPort.IsOpen) { try { // 转换为字节数组并通过串口发送 byte[] buffer = Encoding.UTF8.GetBytes(sendData); sPort.Write(buffer, 0, buffer.Length); } catch (Exception ex) { MessageBox.Show("COM发送数据失败!"); } } } private void sPort0_DataReceived(object sender, SerialDataReceivedEventArgs e) { string end_str=dataGridView.Rows[0].Cells[7].FormattedValue.ToString(); // 创建临时存储空间保存本次读取的结果 byte[] buffer = new byte[sPort_0.BytesToRead]; int bytesReadCount = sPort_0.Read(buffer, 0, buffer.Length); // 追加新获取的内容至全局累积变量中 string newDataString = Encoding.UTF8.GetString(buffer, 0, bytesReadCount); receivedDataBuffer0.Append(newDataString); if (end_str == "/r" || end_str == "/n" || end_str == "/r/n") { int endIndex = 0; if (end_str == "/r") { endIndex = receivedDataBuffer0.ToString().LastIndexOf("\r"); } else if (end_str == "/n") { endIndex = receivedDataBuffer0.ToString().LastIndexOf("\n"); } else if (end_str == "/r/n") { endIndex = receivedDataBuffer0.ToString().LastIndexOf("\r\n"); } if (endIndex > 0) { // 提取消息主体部分 string completeMessage = receivedDataBuffer0.ToString(0, endIndex).Trim(); // 清理缓冲区保留剩余未解析的部分 receivedDataBuffer0.Remove(0, receivedDataBuffer0.Length); // 输出处理后的结果 sPort0_ReceiveStr = completeMessage; // 执行进一步业务逻辑... } } else if (end_str == "" || end_str == "无") { Thread.Sleep(100); // 提取消息主体部分 string completeMessage = receivedDataBuffer0.ToString().Trim(); // 清理缓冲区保留剩余未解析的部分 receivedDataBuffer0.Remove(0, receivedDataBuffer0.Length); // 输出处理后的结果 sPort0_ReceiveStr = completeMessage; // 执行进一步业务逻辑... } } private void sPort1_DataReceived(object sender, SerialDataReceivedEventArgs e) { string end_str = dataGridView.Rows[1].Cells[7].FormattedValue.ToString(); // 创建临时存储空间保存本次读取的结果 byte[] buffer = new byte[sPort_1.BytesToRead]; int bytesReadCount = sPort_1.Read(buffer, 0, buffer.Length); // 追加新获取的内容至全局累积变量中 string newDataString = Encoding.UTF8.GetString(buffer, 0, bytesReadCount); receivedDataBuffer1.Append(newDataString); if (end_str == "/r" || end_str == "/n" || end_str == "/r/n") { int endIndex = 0; if (end_str == "/r") { endIndex = receivedDataBuffer1.ToString().LastIndexOf("\r"); } else if (end_str == "/n") { endIndex = receivedDataBuffer1.ToString().LastIndexOf("\n"); } else if (end_str == "/r/n") { endIndex = receivedDataBuffer1.ToString().LastIndexOf("\r\n"); } if (endIndex > 0) { // 提取消息主体部分 string completeMessage = receivedDataBuffer1.ToString(0, endIndex).Trim(); // 清理缓冲区保留剩余未解析的部分 receivedDataBuffer1.Remove(0, receivedDataBuffer1.Length); // 输出处理后的结果 sPort1_ReceiveStr = completeMessage; // 执行进一步业务逻辑... } } else if (end_str == "" || end_str == "无") { Thread.Sleep(100); // 提取消息主体部分 string completeMessage = receivedDataBuffer1.ToString().Trim(); // 清理缓冲区保留剩余未解析的部分 receivedDataBuffer1.Remove(0, receivedDataBuffer1.Length); // 输出处理后的结果 sPort1_ReceiveStr = completeMessage; // 执行进一步业务逻辑... } } private void sPort2_DataReceived(object sender, SerialDataReceivedEventArgs e) { string end_str = dataGridView.Rows[2].Cells[7].FormattedValue.ToString(); // 创建临时存储空间保存本次读取的结果 byte[] buffer = new byte[sPort_2.BytesToRead]; int bytesReadCount = sPort_2.Read(buffer, 0, buffer.Length); // 追加新获取的内容至全局累积变量中 string newDataString = Encoding.UTF8.GetString(buffer, 0, bytesReadCount); receivedDataBuffer2.Append(newDataString); if (end_str == "/r" || end_str == "/n" || end_str == "/r/n") { int endIndex = 0; if (end_str == "/r") { endIndex = receivedDataBuffer2.ToString().LastIndexOf("\r"); } else if (end_str == "/n") { endIndex = receivedDataBuffer2.ToString().LastIndexOf("\n"); } else if (end_str == "/r/n") { endIndex = receivedDataBuffer2.ToString().LastIndexOf("\r\n"); } if (endIndex > 0) { // 提取消息主体部分 string completeMessage = receivedDataBuffer2.ToString(0, endIndex).Trim(); // 清理缓冲区保留剩余未解析的部分 receivedDataBuffer2.Remove(0, receivedDataBuffer2.Length); // 输出处理后的结果 sPort2_ReceiveStr = completeMessage; // 执行进一步业务逻辑... } } else if (end_str == "" || end_str == "无") { Thread.Sleep(100); // 提取消息主体部分 string completeMessage = receivedDataBuffer2.ToString().Trim(); // 清理缓冲区保留剩余未解析的部分 receivedDataBuffer2.Remove(0, receivedDataBuffer2.Length); // 输出处理后的结果 sPort2_ReceiveStr = completeMessage; // 执行进一步业务逻辑... } } private void sPort3_DataReceived(object sender, SerialDataReceivedEventArgs e) { string end_str = dataGridView.Rows[3].Cells[7].FormattedValue.ToString(); // 创建临时存储空间保存本次读取的结果 byte[] buffer = new byte[sPort_3.BytesToRead]; int bytesReadCount = sPort_3.Read(buffer, 0, buffer.Length); // 追加新获取的内容至全局累积变量中 string newDataString = Encoding.UTF8.GetString(buffer, 0, bytesReadCount); receivedDataBuffer3.Append(newDataString); if (end_str == "/r" || end_str == "/n" || end_str == "/r/n") { int endIndex = 0; if (end_str == "/r") { endIndex = receivedDataBuffer3.ToString().LastIndexOf("\r"); } else if (end_str == "/n") { endIndex = receivedDataBuffer3.ToString().LastIndexOf("\n"); } else if (end_str == "/r/n") { endIndex = receivedDataBuffer3.ToString().LastIndexOf("\r\n"); } if (endIndex > 0) { // 提取消息主体部分 string completeMessage = receivedDataBuffer3.ToString(0, endIndex).Trim(); // 清理缓冲区保留剩余未解析的部分 receivedDataBuffer3.Remove(0, receivedDataBuffer3.Length); // 输出处理后的结果 sPort3_ReceiveStr = completeMessage; // 执行进一步业务逻辑... } } else if (end_str == "" || end_str == "无") { Thread.Sleep(100); // 提取消息主体部分 string completeMessage = receivedDataBuffer3.ToString().Trim(); // 清理缓冲区保留剩余未解析的部分 receivedDataBuffer3.Remove(0, receivedDataBuffer3.Length); // 输出处理后的结果 sPort3_ReceiveStr = completeMessage; // 执行进一步业务逻辑... } } private void sPort4_DataReceived(object sender, SerialDataReceivedEventArgs e) { string end_str = dataGridView.Rows[4].Cells[7].FormattedValue.ToString(); // 创建临时存储空间保存本次读取的结果 byte[] buffer = new byte[sPort_4.BytesToRead]; int bytesReadCount = sPort_4.Read(buffer, 0, buffer.Length); // 追加新获取的内容至全局累积变量中 string newDataString = Encoding.UTF8.GetString(buffer, 0, bytesReadCount); receivedDataBuffer4.Append(newDataString); if (end_str == "/r" || end_str == "/n" || end_str == "/r/n") { int endIndex = 0; if (end_str == "/r") { endIndex = receivedDataBuffer4.ToString().LastIndexOf("\r"); } else if (end_str == "/n") { endIndex = receivedDataBuffer4.ToString().LastIndexOf("\n"); } else if (end_str == "/r/n") { endIndex = receivedDataBuffer4.ToString().LastIndexOf("\r\n"); } if (endIndex > 0) { // 提取消息主体部分 string completeMessage = receivedDataBuffer4.ToString(0, endIndex).Trim(); // 清理缓冲区保留剩余未解析的部分 receivedDataBuffer4.Remove(0, receivedDataBuffer4.Length); // 输出处理后的结果 sPort4_ReceiveStr = completeMessage; // 执行进一步业务逻辑... } } else if (end_str == "" || end_str == "无") { Thread.Sleep(100); // 提取消息主体部分 string completeMessage = receivedDataBuffer4.ToString().Trim(); // 清理缓冲区保留剩余未解析的部分 receivedDataBuffer4.Remove(0, receivedDataBuffer4.Length); // 输出处理后的结果 sPort4_ReceiveStr = completeMessage; // 执行进一步业务逻辑... } } //************************************ DataGridView操作方法 ***************************************** #region DataGridView操作方法 private void SaveDataGridViewToCsv(string filePath, DataGridView dgv) { StringBuilder sb = new StringBuilder(); // 添加表头 for (int colIdx = 0; colIdx < dgv.Columns.Count; colIdx++) { sb.Append(dgv.Columns[colIdx].HeaderText); if (colIdx != dgv.Columns.Count - 1) sb.Append(","); } sb.AppendLine(); // 遍历所有行并将数据追加到字符串中 foreach (DataGridViewRow row in dgv.Rows) { for (int cellIdx = 0; cellIdx < dgv.Columns.Count; cellIdx++) { if (dgv.Columns[cellIdx] is DataGridViewComboBoxColumn comboBoxCol) { sb.Append(row.Cells[cellIdx].FormattedValue); // 获取 ComboBox 显示值 } else if (dgv.Columns[cellIdx] is DataGridViewCheckBoxColumn checkBoxCol) { sb.Append(row.Cells[cellIdx].EditedFormattedValue.ToString()); // 获取 CheckBox 勾选状态 } else { sb.Append(row.Cells[cellIdx].Value?.ToString() ?? ""); // 普通文本列 } if (cellIdx != dgv.Columns.Count - 1) sb.Append(","); } sb.AppendLine(); } // 写入文件 System.IO.File.WriteAllText(filePath, sb.ToString(), Encoding.UTF8); } private void LoadCsvToFixedDataGridView(string filePath, DataGridView dgv) { dgv.Rows.Clear(); try { List<string[]> rowsData = new List<string[]>(); using (StreamReader sr = new StreamReader(filePath)) { string line; int rowIndex = 0; while ((line = sr.ReadLine()) != null) { if (rowIndex == 0) { rowIndex++; continue; } // 跳过表头 string[] rowData = line.Split(','); rowsData.Add(rowData); } } foreach (var rowData in rowsData) { object[] valuesToAdd = new object[dgv.Columns.Count]; for (int i = 0; i < dgv.Columns.Count; i++) { if (dgv.Columns[i] is DataGridViewComboBoxColumn comboBoxCol) { valuesToAdd[i] = comboBoxCol.Items.Cast<object>() .FirstOrDefault(item => item.ToString().Equals(rowData[i], StringComparison.OrdinalIgnoreCase)); } else if (dgv.Columns[i] is DataGridViewCheckBoxColumn checkBoxCol) { valuesToAdd[i] = bool.TryParse(rowData[i], out bool isChecked) ? isChecked : false; } else { valuesToAdd[i] = rowData[i]; } } dgv.Rows.Add(valuesToAdd); } } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(dgv.Name.ToString() + " Failed to load data from CSV file." + Environment.NewLine + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } // 判断是否有足够的行可删 if (dgv.Rows.Count > 1) { // 获取最后一个非新行的索引 int lastIndex = dgv.Rows.Count - 2; // 移除该行 dgv.Rows.RemoveAt(lastIndex); } } #endregion private void ContBackgWork_modbusrtu0() { while (true) { try { modbusRtuInt_0 = modbusrtu0.ReadHoldingRegisters(0, 10); } catch { } Thread.Sleep(10); } } private void ContBackgWork_modbusrtu1() { while (true) { try { modbusRtuInt_1 = modbusrtu1.ReadHoldingRegisters(0, 10); } catch { } Thread.Sleep(10); } } private void ContBackgWork_modbusrtu2() { while (true) { try { modbusRtuInt_2 = modbusrtu2.ReadHoldingRegisters(0, 10); } catch { } Thread.Sleep(10); } } private void ContBackgWork_modbusrtu3() { while (true) { try { modbusRtuInt_3 = modbusrtu3.ReadHoldingRegisters(0, 10); } catch { } Thread.Sleep(10); } } private void ContBackgWork_modbusrtu4() { while (true) { try { modbusRtuInt_4 = modbusrtu4.ReadHoldingRegisters(0, 10); } catch { } Thread.Sleep(10); } } private void timer1_Tick(object sender, EventArgs e) { label1.Text = sPort0_ReceiveStr; label2.Text = sPort1_ReceiveStr; label3.Text = sPort2_ReceiveStr; }
07-19
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值