stringbuilder 和 s+=的效率比较,以及by val 和by ref 的效率比较

本文通过实例代码对比了VB中使用StringBuilder和StringJoin处理字符串集合时的性能表现,发现在数量较大时StringBuilder明显优于StringJoin。同时,探讨了函数传参byval和byref在不同条件下的效率差异。

结论,

1,在数量极小时,stringbuilder并不比s+= 效率高。

2,在数量较大时,stringbuilder 显然比s+=效率高。

3,函数传值 byval和传参考by ref通常情况(所传递的对象不大)下,效率几无区别。

VB代码如下,

   Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click


        Dim col As New NameValueCollection
        col.Add("boat_165", "威士特丹号ms Westerdam")
        col.Add("boat_180", "海洋帝王号Majesty of the Seas")
        col.Add("boat_190", "诗歌号MSC Poesia")
        col.Add("boat_195", "海洋航行者号Voyager of the Seas")
        col.Add("boat_196", "海洋领航者号Navigator of the Seas")
        col.Add("boat_197", "海洋水手号Mariner of the Seas")
        col.Add("boat_198", "海洋探险者号Explorer of the Seas")
        col.Add("boat_199", "海洋自由号Freedom of the Seas")
        col.Add("boat_200", "海洋富丽号Grandeur of the seas")
        col.Add("boat_201", "海洋幻丽号Enchantment of the Seas")
        col.Add("boat_202", "海洋梦幻号Vision of the Seas")
        col.Add("boat_203", "海洋荣光号Splendour of the Seas")
        col.Add("boat_205", "海洋迎风号Rhapsody of the Seas")
        col.Add("boat_206", "尖峰号Celebrity Summit")
        col.Add("boat_207", "千禧号Celebrity Millennium")
        col.Add("boat_208", "无极号Celebrity Infinity")
        col.Add("boat_209", "星座号Celebrity Constellation")
        col.Add("boat_210", "世纪号Celebrity Century")
        col.Add("boat_211", "海洋冒险者号Adventure of the Seas")
        col.Add("boat_212", "银星号Mercury")
        col.Add("boat_213", "阿姆斯特丹号ms Amsterdam")
        col.Add("boat_214", "诺丹号ms Noordam")
        col.Add("boat_215", "如德丹号ms Zuiderdam")
        col.Add("boat_216", "欧仕特丹号ms Oosterdam")
        col.Add("boat_275", "海洋神话号Legend of the seas")
        col.Add("boat_350", "经典号Costa Classica")
        col.Add("boat_353", "海洋绿洲号Oasis of the seas")
        col.Add("boat_354", "新浪漫号Costa neoRomantica")
        col.Add("boat_357", "欧偌丹号ms Eurodam ")
        col.Add("boat_401", "爱兰歌娜号Costa Allegra")
        col.Add("boat_402", "处女星号SuperStar Virgo")
        col.Add("boat_413", "幻想曲号MSC Fantasia")
        col.Add("boat_425", "辉煌号MSC  Splendida")
        col.Add("boat_429", "挪威爱彼号Norwegian Epic")
        col.Add("boat_444", "挪威翡翠号Norwegian Jade")
        col.Add("boat_453", "奥德赛号Seabourn Odyssey ")
        col.Add("boat_463", "星辰公主号Star Princess")
        col.Add("boat_464", "天枰星号SuperStar Libra")
        col.Add("boat_466", "双鱼星号Star Pisces")
        col.Add("boat_467", "命运女神号Costa Magica")
        col.Add("boat_468", "挪威宝石号Norwegian Jewel")
        col.Add("boat_469", "炫目号Costa Luminosa")
        col.Add("boat_470", "唯美号Costa Deliziosa")
        col.Add("boat_471", "华伦丹号ms Volendam")
        col.Add("boat_472", "皇冠公主号Crown Princess")
        col.Add("boat_473", "海洋魅丽号Allure of the Seas")
        col.Add("boat_476", "华丽号MSC Magnifica")
        col.Add("boat_477", "音乐号MSC Musica")
        col.Add("boat_478", "美国之傲号Pride of America")
        col.Add("boat_479", "维丹号ms Veendam")
        col.Add("boat_480", "新阿姆斯特丹号ms Nieuw Amsterdam")
        col.Add("boat_481", "海洋光辉号Brilliance of the Seas")
        col.Add("boat_482", "挪威珠宝号Norwegian Gem")
        col.Add("boat_483", "红宝石公主号Ruby Princess")
        col.Add("boat_484", "黄金公主号Golden Princess")
        col.Add("boat_485", "至尊公主号Grand Princess")
        col.Add("boat_486", "翡翠公主号Emerald Princess")
        col.Add("boat_487", "加勒比公主号Caribbean Princess")
        col.Add("boat_488", "珊瑚公主号Coral Princess")
        col.Add("boat_489", "海岛公主号Island Princess")
        col.Add("boat_490", "钻石公主号Diamond Princess ")
        col.Add("boat_491", "皇家公主号Royal Princess")
        col.Add("boat_492", "蓝宝石公主号Sapphire Princess")
        col.Add("boat_493", "太阳公主号Sun Princess")
        col.Add("boat_494", "黎明公主号Dawn Princess")
        col.Add("boat_495", "碧海公主号Sea Princess")
        col.Add("boat_496", "大溪地公主号Tahitian Princess")
        col.Add("boat_497", "太平洋公主号Pacific Princess")
        col.Add("boat_498", "歌剧号MSC Opera")
        col.Add("boat_499", "抒情号MSC Lirica")
        col.Add("boat_500", "序曲号MSC Sinfonia")
        col.Add("boat_501", "和睦号MSC Armonia")
        col.Add("boat_502", "管乐号MSC Orchestra")
        col.Add("boat_503", "挪威明珠号Norwegian Pearl")
        col.Add("boat_505", "海洋自主号Liberty of the Seas ")
        col.Add("boat_507", "奇观号Disney Wonder")
        col.Add("boat_508", "海皇号Monarch of the Seas")
        col.Add("boat_509", "挪威天空号Norwegian Sky")
        col.Add("boat_510", "海洋独立号Independence of the Seas ")
        col.Add("boat_511", "海洋灿烂号Radiance of the Seas")
        col.Add("boat_512", "挪威精神号Norwegian Spirit")
        col.Add("boat_513", "挪威之晨号Norwegian Dawn")
        col.Add("boat_514", "宝瓶星号Star Aquarius")
        col.Add("boat_515", "水晶宁静号Crystal Serenity")
        col.Add("boat_516", "辉宏号Costa Favolosa")
        col.Add("boat_517", "海洋公主号Ocean Princess")
        col.Add("boat_518", "维多利亚号Costa Victoria")
        col.Add("boat_520", "神曲号MSC Divina")
        col.Add("boat_521", "协和号Costa Concordia")
        col.Add("boat_522", "银云号Silver Cloud")
        col.Add("boat_523", "银风号Silver Wind")
        col.Add("boat_524", "银影号Silver Shadow")
        col.Add("boat_525", "银啸号Silver Whisper")
        col.Add("boat_526", "银神号Silver Spirit ")
        col.Add("boat_527", "银海探索号Silver Explorer")
        col.Add("boat_528", "交响乐号Crystal Symphony")
        col.Add("boat_529", "远征号Celebrity Xpedition")
        col.Add("boat_530", "极致号Celebrity Solstice")
        col.Add("boat_531", "季候号Celebrity Equinox")
        col.Add("boat_532", "新月号Celebrity Eclipse")
        col.Add("boat_533", "嘉印号Celebrity Silhouette")
        col.Add("boat_534", "梦想号Disney Dream")
        col.Add("boat_535", "前进号FRAM")
        col.Add("boat_536", "50年胜利号")
        col.Add("boat_537", "海洋玫瑰号OCEAN ROSE")
        col.Add("boat_538", "大西洋号Atlantica Atlantica")
        col.Add("boat_539", "传奇号Seabourn Legend")
        col.Add("boat_540", "精灵号Seabourn Spirit")
        col.Add("boat_541", "旅行者号Seabourn Sojourn")
        col.Add("boat_542", "探索号Seabourn Quest")
        col.Add("boat_543", "自豪号Seabourn Pride")
        col.Add("boat_545", "创意号Carnival Imagination")
        col.Add("boat_546", "地中海号Costa Mediterranea")
        col.Add("boat_547", "光辉号Carnival Splendor")
        col.Add("boat_548", "光荣号Carnival Glory")
        col.Add("boat_551", "海洋旋律号Serenade of the Seas")
        col.Add("boat_552", "海洋珠宝号Jewel of the Seas")
        col.Add("boat_553", "欢欣号Carnival Elation")
        col.Add("boat_554", "幻想号Disney Fantasy")
        col.Add("boat_555", "佳名号Carnival Sensation")
        col.Add("boat_557", "凯旋号Carnival Triumph")
        col.Add("boat_558", "乐园号Carnival Paradise")
        col.Add("boat_559", "雷丹号ms Ryndam")
        col.Add("boat_560", "灵感号Carnival Inspiration")
        col.Add("boat_561", "鹿特丹号ms Rotterdam")
        col.Add("boat_562", "马士丹号ms Maasdam")
        col.Add("boat_563", "美恋号Costa Fascinosa")
        col.Add("boat_564", "梦幻号Carnival Fantasy")
        col.Add("boat_565", "魔力号Disney Magic")
        col.Add("boat_566", "魔力号Carnival Magic")
        col.Add("boat_570", "挪威飞鸟号Norwegian Breakaway")
        col.Add("boat_574", "挪威太阳号Norwegian Sun")
        col.Add("boat_577", "挪威之星号Norwegian Star")
        col.Add("boat_580", "普林盛丹号ms Prinsendam")
        col.Add("boat_582", "清风号Carnival Breeze")
        col.Add("boat_583", "塞琳娜号Costa Serena")
        col.Add("boat_584", "尚丹号ms Zaandam")
        col.Add("boat_585", "神往号Carnival Ecstasy")
        col.Add("boat_586", "神逸号Carnival Fascination")
        col.Add("boat_587", "胜利号Carnival Victory")
        col.Add("boat_588", "史特丹号ms Statendam")
        col.Add("boat_589", "太平洋号Costa Pacifica")
        col.Add("boat_592", "幸运号Costa Fortuna")
        col.Add("boat_593", "旋律号MSC Melody")
        col.Add("boat_594", "英勇号Carnival Valor")
        col.Add("boat_595", "征服号Carnival Conquest")
        col.Add("boat_596", "自豪号Carnival Pride")
        col.Add("boat_598", "自由号Carnival Freedom")
        col.Add("boat_599", "自主号Carnival Liberty")
        col.Add("boat_600", "传奇号Carnival Legend")
        col.Add("boat_601", "佳运号Carnival Destiny")
        col.Add("boat_602", "奇迹号Carnival Miracle")
        col.Add("boat_603", "双子星号")
        col.Add("boat_604", "珍爱号MSC Preziosa")

        Dim date1 As DateTime
        Dim s As String
       
        date1 = Now
        For i = 0 To 10000
            s = PrintKeysAndValues1(col)
        Next
        Response.Write("<hr>it take " + (Now - date1).Duration.Ticks.ToString + " to call by value by stringbuilder </hr>")

        date1 = Now
        For i = 0 To 10000
            s = PrintKeysAndValues2(col)
        Next
        Response.Write("<hr>it take " + (Now - date1).Duration.Ticks.ToString + " to call by value by string join </hr>")


        date1 = Now
        For i = 0 To 10000
            s = PrintKeysAndValues3(col)
        Next
        Response.Write("<hr>it take " + (Now - date1).Duration.Ticks.ToString + " to call by ref by stringbuilder </hr>")


        date1 = Now
        For i = 0 To 10000
            s = PrintKeysAndValues4(col)
        Next
        Response.Write("<hr>it take " + (Now - date1).Duration.Ticks.ToString + " to callby ref by string join </hr>")


    End Sub

     

    Public Shared Function PrintKeysAndValues1(ByVal myCol As NameValueCollection) As String
        Dim sbd As New StringBuilder

        For Each s In myCol.AllKeys
            sbd.Append(s + ":" + myCol(s) + ";")
        Next s
        Return sbd.ToString
    End Function 'PrintKeysAndValues

    Public Shared Function PrintKeysAndValues2(ByVal myCol As NameValueCollection) As String
        Dim sbd As String = ""

        For Each s In myCol.AllKeys
            sbd += (s + ":" + myCol(s) + ";")
        Next s
        Return sbd.ToString
    End Function 'PrintKeysAndValues


    Public Shared Function PrintKeysAndValues3(ByRef myCol As NameValueCollection) As String
        Dim sbd As New StringBuilder

        For Each s In myCol.AllKeys
            sbd.Append(s + ":" + myCol(s) + ";")
        Next s
        Return sbd.ToString
    End Function 'PrintKeysAndValues

    Public Shared Function PrintKeysAndValues4(ByRef myCol As NameValueCollection) As String
        Dim sbd As String = ""

        For Each s In myCol.AllKeys
            sbd += (s + ":" + myCol(s) + ";")
        Next s
        Return sbd.ToString
    End Function 'PrintKeysAndValues


输 出结果如下:

it take 6690383 to call by value by stringbuilder
it take 20331163 to call by value by string join
it take 6490371 to call by ref by stringbuilder
it take 20631180 to call by ref by string join


这是前端<template> <div class="historyData_page" style="display: flex; margin-bottom: 0px; width: 100%"> <div style="width: 100%"> <div class="content"> <label><strong>工序号</strong></label> <el-select placeholder="请选择工序号" v-model="processColumnParams.process_no" clearable style="width: 250px"> <el-option v-for="item in this.$store.state.commonProcessList" :key="item.process_no" :label="item.process_no + item.details" :value="item.process_no"> </el-option> </el-select> <label><strong>主条形码</strong></label> <el-input placeholder="请输入主条形码" v-model="selectParams.bar_no" clearable style="width: 300px"> </el-input> <label><strong>结果</strong></label> <el-select placeholder="请选择查询结果" v-model="selectParams.ok_flag" clearable style="width: 150px"> <el-option v-for="item in $t('histortData.flag_options')" :key="item.value" :label="item.label" :value="item.value"> </el-option> </el-select> <label><strong>选择时间范围</strong></label> <el-date-picker type="datetime" placeholder="选择开始时间" v-model="selectParams.startTime" default-time="12:00:00"> </el-date-picker> <el-date-picker type="datetime" placeholder="选择结束时间" v-model="selectParams.endTime" default-time="12:00:00"> </el-date-picker> <el-button style="margin: 0 0 0 10px" type="primary" icon="el-icon-search" @click="SearchTable">搜索</el-button> <el-button style="margin: 0 10px 0 10px" type="primary" icon="el-icon-refresh" @click="resetInput">重置</el-button> </div> <div style="margin: 5px 0 10px 10px"> <el-button type="primary" plain icon="el-icon-plus" @click="dialogFormVisible = true">{{ "新增" }} </el-button> <el-button type="danger" plain icon="el-icon-delete">{{ "删除" }} </el-button> <el-button type="warning" plain icon="el-icon-download" @click="handleDownload">{{ "导出" }} </el-button> </div> <div class="tab_Data"> <el-table :data="tableData.slice((currentPage - 1) * PageSize, currentPage * PageSize)" style="width: 100%" height="1115" border :cell-style="cellStyle" :header-cell-style="{ background: '#f5f7fa', color: '#000000', }" v-loading="loading" ref="tableRef" @selection-change="selectionLineChangeHandle" > <af-table-column type="selection"></af-table-column> <template v-for="(item, index) in processTableColumnName"> <af-table-column v-if="item.type == 'bar'" :key="index" :label="item.label" :prop="item.name" fixed> </af-table-column> <af-table-column v-else-if="item.type == 'img'" :key="index" :label="item.label" :prop="item.name"> <template slot-scope="scope"> <el-button type="text" @click="SearchProcessFile(scope.row.bar_no, processColumnParams.process_no, item.label, scope.row.do_time)"> {{ item.label }} </el-button> </template> </af-table-column> <af-table-column v-else-if="item.type == 'csv'" :key="index" :label="item.label" :prop="item.name"> <template slot-scope="scope"> <el-button type="text" @click="SearchCsvFile(scope.row.bar_no, processColumnParams.process_no, item.label, scope.row.do_time)"> {{ item.label }} </el-button> </template> </af-table-column> <af-table-column v-else :key="index" :prop="item.name" :label="item.label"> </af-table-column> </template> </el-table> <div class="tabListPage"> <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="pageSizes" :page-size="PageSize" layout="total, sizes, prev, pager, next, jumper" :total="totalCount"> </el-pagination> </div> </div> </div> <!-- 照片弹框 --> <el-dialog :visible.sync="imageDialogVisible" width="40%"> <div> <span class="demonstration">{{ ProcessFile.name }}</span ><br /> <span class="demonstration">{{ ProcessFile.bar_no }}</span ><br /> <span class="demonstration">{{ image.picPath }}</span> </div> <div> <el-image :src="image.path" :preview-src-list="srcList"></el-image> </div> </el-dialog> <!-- csv弹框 --> <el-dialog :visible.sync="csvDialogVisible" width="60%"> <!-- <div> <el-button type="primary" icon="el-icon-download" @click="csvDownload">{{ 111 }}</el-button> </div> --> <div> <span class="demonstration">{{ csvFile.bar_no }}</span> </div> <div class="main" ref="chartDom" style="widows: 1200px; height: 400px"></div> </el-dialog> </div> </template> <script> import api from "@/api"; import { saveJsonToExcel } from "@/utils/xlsx"; export default { data() { return { processColumnParams: { process_no: "", eqpt_status: "1", }, routerValue: {}, selectParams: { process_no: "", bar_no: "", ok_flag: "All", startTime: "", endTime: "", }, image: { name: "", path: "", picPath: "", }, imageDialogVisible: false, csvDialogVisible: false, searchedImage: false, ProcessFile: { bar_no: "", process_no: "", name: "", lang: "zh", do_time: "" }, plcadress: "", interactionvalue: "", tableData: [], totalCount: 1, currentPage: 1, PageSize: 15, pageSizes: [5, 15, 30, 40], dialogFormVisible: false, modifyDialogFormVisible: false, formDialog: { Process_no: "", Details: "", }, labelPosition: "left", selectedRows: [], processTableColumnName: [], srcList: [], loading: true, // 查询csv文件参数 csvFile: { bar_no: "", process_no: "", name: "", lang: "", do_time: "" }, //曲线数据 csvChart: [], }; }, computed: { change() { this.selectParams = this.$route.params.value == null ? this.selectParams : this.$route.params.value; } }, watch: { change(val) { console.log(val) } }, created() { console.log(this.$route.params.value); console.log(this.selectParams); this.selectParams = this.$store.state.historyData; this.processColumnParams.process_no = this.selectParams.process_no; console.log("this.selectParams"); this.SearchTable(); }, methods: { setinfor() { //console.log(this.selectParams); this.$store.dispatch("historyData", this.selectParams); }, SearchTable() { // console.log(this.selectParams); this.loading = true; this.selectParams.process_no = this.processColumnParams.process_no; console.log(this.selectParams.process_no); if (this.processColumnParams.process_no == "") { this.$message.warning("请先选择要查询的工序号!"); } else if (this.processColumnParams.startTime == "") { this.$message.warning("请先选择要查询的起始时间!"); } else if (this.processColumnParams.endTime == "") { this.$message.warning("请先选择要查询的截止时间!"); } else { this.processTableColumnName = []; for (let index = 0; index < this.$t("histortData.processFixedTableColumnName").length; index++) { const element = this.$t("histortData.processFixedTableColumnName")[index]; this.processTableColumnName.push(element); } api.getProcessTableColumnName("/ProcessTableColumnName", this.processColumnParams).then((data) => { for (let index = 0; index < data.data.length; index++) { const element = data.data[index]; this.processTableColumnName.push(element); } console.log(data.data); }); api.getProcessProperties("/ProcessProperties", this.selectParams).then((data) => { console.log(data.data); this.loading = false; this.totalCount = data.data.length; this.tableData = data.data; console.log(data.data); this.setinfor(); //数据存储 }); } }, //获取工序图片 产品码、工序、图片名 SearchProcessFile(val, val2, val3, val4) { console.log(val, val2, val3, val4); this.ProcessFile.bar_no = val; this.ProcessFile.process_no = val2; this.ProcessFile.name = val3; this.ProcessFile.do_time = val4; this.ProcessFile.lang = "zh"; // 显示指定产品的指定图片 api.getProcessFileSingle("/ProcessFileSingle", this.ProcessFile).then((data) => { // 清空image数据 this.image = []; // 清空 this.srcList = []; this.imageDialogVisible = true; if (data.data[0].path == "") { this.searchedImage = false; } else { this.image = data.data[0]; for (let index = 0; index < data.data.length; index++) { const element = data.data[index].path; this.srcList.push(element); } this.searchedImage = true; } }); }, //获取csv SearchCsvFile(val, val2, val3, val4) { this.csvFile.bar_no = val; this.csvFile.process_no = val2; this.csvFile.name = val3; this.csvFile.do_time = val4; this.csvFile.lang = "zh"; // 获取最新图片 //this.csvColumnName = this.$t("PointInspectionResult.VibrationCsvColumnName"); api.getReadCurves("/ReadCurves", this.csvFile).then((data) => { //this.csvChart = data.data; this.csvDialogVisible = true; console.log(this.csvFile); console.log(data.data); this.initChart(data.data); }); }, initChart(data) { this.$nextTick(() => { this.csvChart = data; var chartDom = this.$refs.chartDom; // 检查 DOM 元素是否存在 if (!chartDom) { console.error("chartDom is not found"); return; } // 检查 DOM 元素的宽度高度 console.log("chartDom width:", chartDom.offsetWidth, "height:", chartDom.offsetHeight); var myChart = this.$echarts.init(chartDom); var xAxis = []; var yAxis = []; this.csvChart.forEach((el) => { xAxis.push(el.x_Absolute); yAxis.push(el.y); }); yAxis = data.map((el) => parseFloat(el.y)); console.log("xAxis:", xAxis); console.log("yAxis:", yAxis); var option = { tooltip: { trigger: "axis", formatter: (params) => { const xValue = params[0].axisValue; const yValue = params[0].data; return `${xValue}:${yValue}`; }, axisPointer: { type: "cross", label: { backgroundColor: "#6a7985", }, }, }, xAxis: { type: "category", data: xAxis, name: "单位(s)", axisLabel: { show: true, showMaxLabel: true, showMinLabel: true, }, }, yAxis: { type: "value", name: "单位(N)", //max: 2, }, series: [ { data: yAxis, type: "line", }, ], }; myChart.setOption(option); }); }, selectionLineChangeHandle(val) { // console.log(this.selectedRows); this.selectedRows = val; }, resetInput() { (this.fieldname = ""), (this.plcadress = ""), (this.interactionvalue = ""); }, modifyData(val) { this.modifyDialogFormVisible = true; }, cellStyle({ row, column, rowIndex, columnIndex }) { // NG字样红色显示 // for (let index = 0; index < this.$t("ShowResult.tableColumnName").length; index++) { // const element = this.$t("ShowResult.tableColumnName")[index].name; // if (row[element] == "NG" && column.property == element) { // return "color:red"; // } // } // 数据超限红色显示 // for (let i = 0; i < this.ParamatesLimit.length; i++) { // const element = this.ParamatesLimit[i].name; // if ((Number(this.ParamatesLimit[i].up_limit) < Number(row[element]) || Number(row[element]) < Number(this.ParamatesLimit[i].down_limit)) && column.property == element) { // return "color:red"; // } // } for (let index = 0; index < this.processTableColumnName.length; index++) { const element = this.processTableColumnName[index].name; if (row[element] == "NG" && column.property == element) { return "color:red"; } } }, // 导出数据 handleDownload() { var tabHandle = []; //导出表头 for (let index = 0; index < this.processTableColumnName.length; index++) { const element = this.processTableColumnName[index]; if (element.type != "img" && element.type != "csv") { tabHandle.push(element.label); } } saveJsonToExcel(this.tableData, tabHandle, "OP" + this.processColumnParams.process_no + ".xlsx"); }, // 每页显示的条数 handleSizeChange(val) { // 改变每页显示的条数 this.PageSize = val; // 注意:在改变每页显示的条数时,要将页码显示到第一页 this.currentPage = 1; }, // 显示第几页 handleCurrentChange(val) { // 改变默认的页数 this.currentPage = val; }, }, updated() { // tableRef是表格的ref属性值 if (this.$refs.tableRef && this.$refs.tableRef.doLayout) { this.$refs.tableRef.doLayout(); } }, }; </script> <style scoped lang="less"> .el-menu { width: 200px; } .tab_Data { // width: 100%; /* margin-top: 30px; margin-left: 10px; margin-right: 10px; */ } .content { // justify-content: flex-start; // display: flex; } </style> 这是后端using SanHuaMesApiServer.Models; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.VisualBasic.FileIO; using System.Data; using System.Globalization; using System.Text; using SanHuaMesApiServer.Helps; namespace SanHuaMesApiServer.Controllers { [Route("api/[controller]")] [ApiController] public class ProcessCheckColumnNameController : ControllerBase { [HttpGet] public async Task<IEnumerable<ProcessTableColumnName>> Get([FromQuery] string process_no,string inspection_type,string eqpt_status,string? file_type) { return await Task.Factory.StartNew(() => { StringBuilder sb = new StringBuilder(); sb.Append($"select field_name,field_name_cn from SHProcessInspectionPropertyParse where process_no = '{process_no}' and inspection_type = '{inspection_type}' ORDER BY field_name "); DataSet data = SqlHelper.GetTable(CommandType.Text, sb.ToString(), null); StringBuilder sbImag = new StringBuilder(); sbImag.Append($"select name,name_en from GTProcessFileConfig where process_no = '{process_no}' and eqpt_status = '{eqpt_status}' and file_type = '{file_type}'"); DataSet dataImag = SqlHelper.GetTable(CommandType.Text, sbImag.ToString(), null); List<ProcessTableColumnName> temp = new List<ProcessTableColumnName>(); foreach (DataRow row in dataImag.Tables[0].Rows) { temp.Add(new ProcessTableColumnName() { Name = row[1].ToString(), Label = row[0].ToString(), Type = file_type, }); ; ; } foreach (DataRow row in data.Tables[0].Rows) { temp.Add(new ProcessTableColumnName() { Name = row[0].ToString(), Label = row[1].ToString(), Type = "", }); ; ; } return temp.AsEnumerable(); }); } } [Route("api/[controller]")] [ApiController] public class ProcessCheckColumnNameEnController : ControllerBase { [HttpGet] public async Task<IEnumerable<ProcessTableColumnName>> Get([FromQuery] string process_no, string inspection_type, string eqpt_status, string? file_type) { return await Task.Factory.StartNew(() => { StringBuilder sb = new StringBuilder(); sb.Append($"select field_name,field_name_en from SHProcessInspectionPropertyParse where process_no = '{process_no}' and inspection_type = '{inspection_type}' "); DataSet data = SqlHelper.GetTable(CommandType.Text, sb.ToString(), null); StringBuilder sbImag = new StringBuilder(); sbImag.Append($"select name,name_en,file_type from GTProcessFileConfig where process_no = '{process_no}' and eqpt_status = '{eqpt_status}' and file_type = '{file_type}'"); DataSet dataImag = SqlHelper.GetTable(CommandType.Text, sbImag.ToString(), null); List<ProcessTableColumnName> temp = new List<ProcessTableColumnName>(); foreach (DataRow row in dataImag.Tables[0].Rows) { temp.Add(new ProcessTableColumnName() { Name = row[1].ToString(), Label = row[1].ToString(), Type = row[2].ToString(), }); ; ; } foreach (DataRow row in data.Tables[0].Rows) { temp.Add(new ProcessTableColumnName() { Name = row[0].ToString(), Label = row[1].ToString(), Type = "", }); ; ; } return temp.AsEnumerable(); }); } } }报错这个index.js:116 GET https://127.0.0.1:7053/api/ProcessProperties?process_no=20&bar_no=&ok_flag= 400 (Bad Request) settle.js:19 Uncaught (in promise) AxiosError {message: 'Request failed with status code 400', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …} code : "ERR_BAD_REQUEST" config : {transitional: {…}, adapter: Array(3), transformRequest: Array(1), transformResponse: Array(1), timeout: 10000, …} message : "Request failed with status code 400" name : "AxiosError" request : XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 10000, withCredentials: false, upload: XMLHttpRequestUpload, …} response : {data: {…}, status: 400, statusText: '', headers: AxiosHeaders, config: {…}, …} status : 400 stack : "AxiosError: Request failed with status code 400\n at settle (webpack-internal:///./node_modules/axios/lib/core/settle.js:24:12)\n at XMLHttpRequest.onloadend (webpack-internal:///./node_modules/axios/lib/adapters/xhr.js:63:66)\n at Axios.request (webpack-internal:///./node_modules/axios/lib/core/Axios.js:54:41)" [[Prototype]] : Error XMLHttpRequest.send getProcessProperties @ index.js:116 SearchTable @ historyData.vue:197
05-30
1.修改以下代码.js代码使用的是vue开发;.cshtml代码使用的是elementui开发;以及.net代码。功能:选 分类方式 的下拉框 天 月 所有,来进行数据的统计分组 具体显示在 分组方式该列,分组方式 显示涉及到的时间数据库字段为 F_OrderDat,字段值为2025-11-21这种时间;分组方式 显示数据为:1.选中 天 显示数据为2025-11-21,2.选中 月 显示数据为 2025-11,3.选中 所有 显示所有数据。 .js代码: var refreshGirdData; var bootstrap = function ($, UtSoft) { new Vue({ el: '#remainingSampleBack', filters: { //日期格式化 dateFormat(val) { let value = '' if (val) { const arr = val.split(' ') if (arr.length > 0) { value = arr[0] } } return value }, }, data: function () { return { tabName: 'statistic1', tabDataArr: [ { label: '排单统计', name: 'statistic1' }, { label: '受理统计', name: 'statistic2' } ], loading: false, loadingTxt: '', props: { multiple: true }, PayTypeNameArr: [], salerOptions: [], tableConfig: { apiUrl: { statistic1: '/Order/Statistics/GetBuilderOrderData', statistic2: '/Order/Statistics/GetReceiveOrderData' }, tableData: [], tableDataAll: [], tableColumnAll: [], tableColumn: { statistic1: [ { title: '排单人', field: 'F_CreateUserName', width: 200 }, { title: '订单数量', field: 'F_OrderNum', width: 180 }, { title: '项目数量', field: 'F_ItemNum', width: 180 }, { title: '分组方式', field: 'F_GroupingType‌', width: 180 }, ], statistic2: [ { title: '受理人', field: 'F_ReceptorName', width: 200 }, { title: '订单数量', field: 'F_OrderNum', width: 180 }, { title: '项目数量', field: 'F_ItemNum', width: 180 }, { title: '分组方式', field: 'F_GroupingType‌', width: 180 }, ] } }, TimeTypeOption: [{ value: 'day', text: '天' }, { value: 'month', text: '月' }, { value: 'all', text: '所有' }], pageConfig: { //每页行数F_IsCutOff rows: 20, // 当前页 page: 1, //总记录数 records: 0, // mainId: 'F_OrderId', //排序列 sidx: 'F_CreateUserName', //排序类型 sord: 'desc', //总页数 total: 0 }, queryParams: { F_Status: -10, TimeType: '', DateArr: [], tableColumnMonth: [], customerType: '基本应收明细', F_SalerName: '', F_Salors: [], }, customConfig: { storage: { visible: true, resizable: true, sort: true, fixed: true }, mode: 'popup' }, selectedArr: [], sampleTypeArr: [], pickerOptions: { shortcuts: [{ text: '最近一周', onClick(picker) { const end = new Date(); const start = new Date(); start.setTime(start.getTime() - 3600 * 1000 * 24 * 7); picker.$emit('pick', [start, end]); } }, { text: '最近一个月', onClick(picker) { const end = new Date(); const start = new Date(); start.setTime(start.getTime() - 3600 * 1000 * 24 * 30); picker.$emit('pick', [start, end]); } }, { text: '最近三个月', onClick(picker) { const end = new Date(); const start = new Date(); start.setTime(start.getTime() - 3600 * 1000 * 24 * 90); picker.$emit('pick', [start, end]); } }] }, } }, created() { this.initData(); }, mounted() { const $sampleLendReturnTable = this.$refs.sampleLendReturnTable const $sampleLendReturnToolbar = this.$refs.sampleLendReturnToolbar if ($sampleLendReturnTable && $sampleLendReturnToolbar) { $sampleLendReturnTable.connect($sampleLendReturnToolbar) } //this.getPageList(); }, methods: function () { return { initData() { const that = this UtSoft.clientdata.getAllAsync('dataItem', { code: 'SampleType', callback: function (data) { _.forEach(data, function (value, key) { that.sampleTypeArr.push({ value: value.value, text: value.text }) }) } }); UtSoft.clientdata.getAllAsync('dataItem', { code: 'PayType', callback: function (data) { _.forEach(data, function (value, key) { that.PayTypeNameArr.push({ value: value.text, label: value.text }) }) } }); UtSoft.httpAsync('GET', '/Order/Statistics/GetDeptSalerList', {}, (data) => { if (data) { console.log("data") console.log(data) that.salerOptions = data } }) }, handleTabClick(obj) { this.queryParams.customerType = this.tabName //switch (this.tabName) { // case 'statistic1': { // const obj = { applyBack: true, cancelApplication: false, rejectApplication: false, confirmBack: false } // this.changeButtonVisible(obj) // } break // case 'statistic2': { // const obj = { applyBack: false, cancelApplication: true, rejectApplication: true, confirmBack: true } // this.changeButtonVisible(obj) // } break // case 'statistic3': { // const obj = { applyBack: false, cancelApplication: false, rejectApplication: false, confirmBack: false } // this.changeButtonVisible(obj) // } break //} this.searchData(); }, searchData() { let that = this that.pageConfig.page = 1; if (that.tabName == 'statistic1') { that.pageConfig.sidx = 'F_CreateUserName' } else { that.pageConfig.sidx = 'F_ReceptorName' } that.getPageList(); }, getPageList() { const params = { pagination: JSON.stringify(this.pageConfig), queryJson: JSON.stringify(this.queryParams) } this.loading = true; this.loadingTxt = '正在加载'; window.setTimeout(() => { debugger UtSoft.httpAsync('GET', this.tableConfig.apiUrl[this.tabName], params, (result) => { this.loading = false; this.loadingTxt = ''; console.log("result") console.log(result) if (result) { this.tableConfig.tableData = result.rows; this.pageConfig.records = result.records; this.pageConfig.total = result.total; this.$nextTick(() => { this.$refs.sampleLendReturnTable.doLayout() }) } else { this.$notify.error({ title: '错误', message: '获取列表失败,请联系管理员处理' }); } }); }, 300); }, handleSalerChange() { const checknodes = this.$refs.salerCascader.getCheckedNodes(); const newArr = [] for (index in checknodes) { newArr.push(checknodes[index].value) } console.log("newArr") console.log(newArr) this.queryParams.F_Salors = newArr }, getTableColumns() { const DateStr = this.queryParams.DateArr.join(',') return new Promise(function (resolve, reject) { $.ajax({ url: top.$.rootUrl + '/Order/ReceiveAmtStatistics/getTableColumns', data: { DateStr: DateStr }, type: "get", dataType: "json", async: false, success: function (data) { //console.log("resolve:",data) resolve(data) }, error: function (data) { reject(data) } }) }) }, handelCheckboxChange({ checked, records }) { this.selectedArr = records; }, ExportData() { let excelName = "" if (this.tabName == "statistic1") { excelName = "排单统计.xlsx"; } else { excelName = "受理统计.xlsx"; } let table = document.querySelector('#sampleLendReturnTable').cloneNode(true); //table.removeChild(table.querySelector(".el-table__fixed"));//删除左侧固定列 //const elTable = this.$refs.table; const ws = XLSX.utils.table_to_sheet(table); const wb = XLSX.utils.book_new(); XLSX.utils.book_append_sheet(wb, ws, 'Sheet1'); const wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' }); saveAs(new Blob([wbout], { type: 'application/octet-stream' }), excelName); }, handlePageChange(pageObj) { switch (pageObj.type) { case 'current': this.pageConfig.page = pageObj.currentPage; break; case 'size': this.pageConfig.rows = pageObj.pageSize; break; } this.getPageList(); } } }() }) } .cshtml代码:@using UtSoft.Util; @{ ViewBag.Title = "逾期统计"; Layout = "~/Views/Shared/_Index.cshtml"; } <style type="text/css" scoped> [v-cloak] { display: none } .custom-container { height: 100%; background-color: #ffffff; } .custom-container .el-main { padding: 0 10px 0 10px; } .custom-container .el-header { height: auto !important; padding: 5px 10px 0 10px; } .el-footer { height: auto !important; padding: 5px 10px !important; } .el-date-editor .el-range-separator { padding: 0px 0px !important; } </style> <div v-cloak id="remainingSampleBack" style="width: 100%;height: 100%;"> <el-container class="custom-container"> <el-header> <el-tabs v-model="tabName" @@tab-click="handleTabClick" style="height: 54px"> <el-tab-pane v-for="(tab,index) in tabDataArr" :label="tab.label" :name="tab.name"></el-tab-pane> </el-tabs> <div style="transition: all .3s; overflow: hidden"> <el-form id="searchClass" :inline="true" :model="queryParams" label-width="auto" size="small"> <el-col :span="24"> <el-tag class="title" style="margin-bottom: 3px"> 受理日期 </el-tag> <el-date-picker v-model="queryParams.DateArr" type="daterange" align="right" unlink-panels size="small" value-format="yyyy-MM-dd" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" style="margin-left:0px;border-top-left-radius:0;border-bottom-left-radius:0;width:250px" :picker-options="pickerOptions"> </el-date-picker> <el-tag class="title" style="margin-bottom: 3px"> 分类方式 </el-tag> <template> <el-select v-model="queryParams.TimeType" placeholder="请选择" style="margin-left:0px;width:100px"> <el-option v-for="item in TimeTypeOption" :key="item.value" :label="item.text" :value="item.value"> </el-option> </el-select> </template> <el-button id="searchData" type="primary" size="small" icon="el-icon-search" @@click="searchData">搜索</el-button> <el-button id="export" type="success" size="small" @@click="ExportData">导出</el-button> </el-col> </el-form> </div> </el-header> <el-main style="overflow-y: hidden"> <el-table :data="tableConfig.tableData" :element-loading-text="loadingTxt" v-loading="loading" style="width: 100%" height="100%" size="small" ref="sampleLendReturnTable" id="sampleLendReturnTable" show-summary border highlight-current-row> @*<el-table-column type="selection" align="center"></el-table-column>*@ @*<el-table-column type="index" label="序号" width="50" align="center" fixed></el-table-column>*@ <template v-for="(column,index) in tableConfig.tableColumn[tabName]"> <el-table-column :key="index" :label="column.title" :fixed="column.fixed" :width="column.width" :prop="column.field" :sortable="column.sortable?true:false" show-overflow-tooltip> </el-table-column> </template> </el-table> </el-main> <el-footer> <vxe-pager style="float:left;" :current-page="pageConfig.page" :page-sizes="[10,15, 20, 30, 50,100,200,500,1000,10000]" :page-size="pageConfig.rows" :total="pageConfig.records" :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']" size="mini" @@page-change="handlePageChange"> </vxe-pager> </el-footer> </el-container> </div> <script type="text/javascript" src="~/Content/lodash/lodash4.17.15.min.js"></script> <link href="~/Content/element-ui/elementui2.13.2.css" rel="stylesheet" /> <script src="~/Content/element-ui/elementui2.13.2.js"></script> <script src="~/Content/Sortable/Sortable.min.js"></script> <link rel="stylesheet" href="~/Content/element-ui/xvetable/style.css"> <!-- 引入脚本 vxe-table --> <script src="~/Content/element-ui/xvetable/xe-utils.js"></script> <script src="~/Content/element-ui/xvetable/vxe-table.js"></script> @Html.AppendJsFile("/Areas/Order/Views/Statistics/BuildOrderStatistic.js") @*导出*@ <script src="~/Content/vue/excel/FileSaver.min.js"></script> <script src="~/Content/vue/excel/xlsx.mini.min.js"></script> .net代码:public DataTable GetBuilderOrderData(Pagination pagination, string queryJson) { try { var queryParam = queryJson.ToJObject(); StringBuilder sqlApp = new StringBuilder(); if (!queryParam["DateArr"].IsEmpty()) { string[] DateRange = queryParam["DateArr"].ToObject<string[]>(); if (DateRange.Length == 2) { sqlApp.Append($"AND (o.F_OrderDate>='{DateRange[0]}' AND o.F_OrderDate<='{DateRange[1]}' )"); } } StringBuilder sqlStr = new StringBuilder($@"select F_CreateUserName, count(F_OrderNo) as F_OrderNum, sum(F_ItemNum) as F_ItemNum, F_RealName as F_Salor from ( select o.F_OrderNo,o.F_CreateUserName,lbu.F_RealName, (select count(F_OrderItemNo) from orderItem oi where oi.F_OrderNo = o.F_OrderNo and oi.F_CalculationType is null) as F_ItemNum from [order] o inner join FciiLims..lr_base_user lbu on lbu.F_EnCode = o.F_SalerNo where 1=1 {sqlApp.ToString()} )f group by F_CreateUserName, F_RealName "); return this.BaseRepository(DBName.TestingRepository).FindTable(sqlStr.ToString(), pagination, 0); } catch (Exception ex) { if (ex is Exception) { throw; } else { throw ExceptionEx.ThrowServiceException(ex); } } }
最新发布
11-26
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值