Compare DataTable list to String List
本文关键字:String List to list DataTable Compare | 更新日期: 2023-09-27 18:13:18
所以我试图从excel导入创建数据表,然后用于其他事情。我知道电子表格的名称,所以我在文档的顶部创建了数据表:
private DataTable Version,Pi_PROCESSPi_PMLIFEPROFILE,PIAPPLICATION,PIRUGGEDISING,ELECTRONICCOMPONENT,HFANDRFCOMPONENTS,HYBRIDANDMULTICHIPMODULE,COTSBOARDS, VARIOUSSUBASSEMBLIES,PARTCOUNT, FAMILYCOUNT;
当读取电子表格时,我有一个列表和一个for循环,将电子表格名称分配给该列表
List<string>ExcelSheets = new List<string>();
excel电子表格列表和数据表声明具有相同的名称
我有一个基于给定表名读取excel电子表格的函数,所以我希望能够做一些像(伪代码):
foreach ExcelSheets{
Datatable = dt.ReadFunction()
}
,其中DataTable是文件顶部声明的数据表。
所以我想说对于列表中的每个Sheet,运行函数并将结果赋值给相应的数据表
编辑:参考代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Web;
using System.Xml;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using System.Data.OleDb;
using System.Reflection;
using System.Text.RegularExpressions;
using S = DocumentFormat.OpenXml.Spreadsheet.Sheets;
using E = DocumentFormat.OpenXml.OpenXmlElement;
using A = DocumentFormat.OpenXml.OpenXmlAttribute;
namespace FidesToRWB
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
#region Strings
string FileType;
string FileDesc1;
string FileDesc2;
string FileQty;
string FileID;
string T_max;
string NLayer;
string NConnection;
string NContact;
string NAnnualCycles;
string NumberOfPins;
string NumberofSMD;
string RiseofTemp;
string PApplied;
string VApplied;
string VContact;
string IContact;
string UNormal;
string LimitandManual;
string NoofManov;
string Louput;
string NDT;
string NST;
string IApplied;
string Qman;
string Qcomponent;
string RAMan;
string Experiance;
private string newLine;
#endregion
private DataTable Version,Pi_PROCESSPi_PMLIFEPROFILE,PIAPPLICATION,PIRUGGEDISING,ELECTRONICCOMPONENT,HFANDRFCOMPONENTS,HYBRIDANDMULTICHIPMODULE,COTSBOARDS, VARIOUSSUBASSEMBLIES,PARTCOUNT, FAMILYCOUNT;
List<string>ExcelSheets = new List<string>();
List<string> phases = new List<string>();
GetDataFromExcel dt = new GetDataFromExcel();
int ColIndex = 0;
int start = 0;
private void btnBrowse_Click(object sender, EventArgs e)
{
OpenFileBox();
}
/// <summary>
/// Reads the file based on the selected grid view.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnRead_Click(object sender, EventArgs e)
{
//Need to check if the combo box is empty first - otherwise we will get an error...
if (cmbSheetSelect.SelectedIndex <= -1)
{
MessageBox.Show("Please select a sheet to display", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
string Sheet = cmbSheetSelect.SelectedItem.ToString();
string TrimmedSheet = Sheet.TrimEnd();
//Enter the start row number in Excel of the data
if (TrimmedSheet == "Pi_PROCESS&Pi_PM&LIFE PROFILE")
{
start = 18;
ColIndex = 16;
}
if (TrimmedSheet == "PI APPLICATION")
{
start = 9;
ColIndex = 4;
}
if (TrimmedSheet == "PI RUGGEDISING")
{
start = 9;
}
if (TrimmedSheet == "ELECTRONIC COMPONENT" || TrimmedSheet == "HF AND RF COMPONENTS" || TrimmedSheet == "HYBRID AND MULTICHIP MODULE" || TrimmedSheet == "COTS BOARDS")
{
start = 70;
ColIndex = 5;
}
if (TrimmedSheet == "VARIOUS SUBASSEMBLIES")
{
start = 70;
}
foreach (var sheetName in ExcelSheets)
{
var prop = Form1.GetType().GetField(sheetName, BindingFlags.NonPublic | BindingFlags.Instance);
prop.SetValue(this, dt.ExtractExcelSheetValuesToDataTable(txtFileLocation.Text, Sheet, start, ColIndex));
}
//DataTable t = dt.ExtractExcelSheetValuesToDataTable(txtFileLocation.Text, Sheet, start, ColIndex);
//dataGridView1.DataSource = t;
}
}
/// <summary>
/// Gets the sheet information
/// </summary>
/// <param name="GetSheetInfo"></param>
public void GetSheetInfo(string fileName)
{
Sheets theSheets = null;
// Open file as read-only.
using (SpreadsheetDocument mySpreadsheet = SpreadsheetDocument.Open(fileName, false))
{
S sheets = mySpreadsheet.WorkbookPart.Workbook.Sheets;
WorkbookPart wbPart;
wbPart = mySpreadsheet.WorkbookPart;
theSheets = wbPart.Workbook.Sheets;
foreach (Sheet item in theSheets)
{
cmbSheetSelect.Items.Add(item.Name);
ExcelSheets.Add(item.Name);
}
}
}
private void txtFileLocation_Click(object sender, EventArgs e)
{
OpenFileBox();
}
public void OpenFileBox()
{
Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "C:''";
openFileDialog1.Filter = "Excel 2007+ (*.xlsx)|*.xlsx";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
// Insert code to read the stream here.
txtFileLocation.Text = openFileDialog1.FileName;
cmbSheetSelect.Enabled = true;
btnRead.Enabled = true;
GetSheetInfo(txtFileLocation.Text);
lblPIP.Text = dt.GetCellValue(txtFileLocation.Text, "Pi_PROCESS&Pi_PM&LIFE PROFILE", "D3");
lblPILF.Text = dt.GetCellValue(txtFileLocation.Text, "Pi_PROCESS&Pi_PM&LIFE PROFILE", "D4");
lblPIRFHF.Text = dt.GetCellValue(txtFileLocation.Text, "Pi_PROCESS&Pi_PM&LIFE PROFILE", "D5");
int x = 20; int y = 20;
for (int i = 18; i < 37; i++)
{
if (dt.GetCellValue(txtFileLocation.Text, "Pi_PROCESS&Pi_PM&LIFE PROFILE", "A"+i.ToString()).ToString() != "")
{
phases.Add(dt.GetCellValue(txtFileLocation.Text, "Pi_PROCESS&Pi_PM&LIFE PROFILE", "A"+i.ToString()).ToString());
}
y += 30;
}
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}
private void label6_Click(object sender, EventArgs e)
{
}
public void GenerateCSV(string fileLoc, string type)
{
//Strings for things.
string csvFilePath = "C:''RWBExport.csv";
var csv = new StringBuilder();
if (type == "ELECTRONIC COMPONENT")
{
newLine = string.Format("{0},{1},{2},{3} {4}", "ID", "Category", "ParamValuesKey", "PartNumber", Environment.NewLine);
csv.Append(newLine);
foreach (DataGridViewRow row in dataGridView1.Rows)
{
//Type
string Type = row.Cells[1].Value.ToString();
Type = Type.Substring(Type.IndexOf('[') + 1);
Type = Type.Remove(Type.Length - 1);
switch (Type)
{
case "ECDS":
FileType = "FID-DS";
break;
default:
MessageBox.Show("Error, no matchin param value");
break;
}
//Appendix 1
string app1 = row.Cells[2].Value.ToString();
app1 = app1.Substring(app1.IndexOf('[') + 1);
app1 = app1.Remove(app1.Length - 1);
switch (app1)
{
#region Switch Case for Semiconductor Case
case "ECDS_01":
FileDesc2 = "THSSP";
break;
case "ECDS_02":
FileDesc2 = "SSSLP";
break;
case "ECDS_03":
FileDesc2 = "SMSLP";
break;
case "ECDS_04":
FileDesc2 = "THPP";
break;
case "ECDS_05":
FileDesc2 = "SSSCP";
break;
case "ECDS_06":
FileDesc2 = "SPLLP";
break;
case "ECDS_07":
FileDesc2 = "SHPSP";
break;
case "ECDS_08":
FileDesc2 = "SHSG";
break;
case "ECDS_09":
FileDesc2 = "THM";
break;
case "ECDS_37":
FileDesc2 = "TSSOP";
break;
case "ECDS_32":
FileDesc2 = "TSOP";
break;
case "ECDS_28":
FileDesc2 = "SO";
break;
default:
FileDesc2 = "BCHIP";
break;
#endregion
}
//Appendix2
string app2 = row.Cells[3].Value.ToString();
app2 = app2.Substring(app2.IndexOf('[') + 1);
app2 = app2.Remove(app2.Length - 1);
switch (app2)
{
#region Switch Case for Semiconductor Type
case "ECDS_10":
FileDesc1 = "LDSD";
break;
case "ECDS_11":
FileDesc1 = "LDRD";
break;
case "ECDS_12":
FileDesc1 = "LDZR";
break;
case "ECDS_13":
FileDesc1 = "LDPD";
break;
case "ECDS_14":
FileDesc1 = "PDTH";
break;
case "ECDS_15":
FileDesc1 = "PDRD";
break;
case "ECDS_16":
FileDesc1 = "PDZR";
break;
case "ECDS_17":
FileDesc1 = "PDPD";
break;
case "ECDS_18":
FileDesc1 = "LTSJ";
break;
case "ECDS_19":
FileDesc1 = "LTSM";
break;
case "ECDS_20":
FileDesc1 = "LTSB";
break;
case "ECDS_21":
FileDesc1 = "PTSB";
break;
case "ECDS_22":
FileDesc1 = "PTSM";
break;
case "ECDS_23":
FileDesc1 = "PTIG";
break;
#endregion
}
//Qty
FileQty = row.Cells[5].Value.ToString();
//ID
FileID = row.Cells[0].Value.ToString();
#region Of things you never want to repeat...add this to that list. Pulls all the variables.
T_max = row.Cells[12].Value.ToString();
NLayer = row.Cells[13].Value.ToString();
NConnection = row.Cells[14].Value.ToString();
NContact = row.Cells[15].Value.ToString();
NAnnualCycles = row.Cells[16].Value.ToString();
NumberOfPins = row.Cells[17].Value.ToString();
NumberofSMD = row.Cells[18].Value.ToString();
string numberOfDS = row.Cells[19].Value.ToString();
RiseofTemp = row.Cells[20].Value.ToString();
PApplied = row.Cells[21].Value.ToString();
VApplied = row.Cells[22].Value.ToString();
VContact = row.Cells[24].Value.ToString();
IContact = row.Cells[25].Value.ToString();
UNormal = row.Cells[26].Value.ToString();
LimitandManual = row.Cells[27].Value.ToString();
NoofManov = row.Cells[28].Value.ToString();
Louput = row.Cells[29].Value.ToString();
NDT = row.Cells[30].Value.ToString();
NST = row.Cells[31].Value.ToString();
IApplied = row.Cells[32].Value.ToString();
Qman = row.Cells[7].Value.ToString();
Qcomponent = row.Cells[8].Value.ToString();
RAMan = row.Cells[9].Value.ToString();
Experiance = row.Cells[10].Value.ToString();
#endregion
//QMAN
string line = FileID + " " + FileType + " " + FileDesc1 + " " + FileDesc2 + " " + FileQty;
//QUAN=1 ADJF=1 DSTYPE=LDSD DSCASE=SSSCP NINC=1 QMAN=HIGH QCOM=HIGH RMAN=VRA EFACT=RMNP PLACE=DNIF NPIN=3 TRCM=TRUSER TEMPR=20 TJA=0 POWEOP=0 STMODE=STCALC VOLT=0.5 VOLTOP=0.5 VOLTRA=1 CHSA=4 DVDC=1 RFHFPF=2.5
var DataLine = string.Format("{0},{1},{2},{3} {4}",
FileID, FileType,
"QUAN=" + FileQty + " DSTYPE=" + FileDesc1 + " DSCASE=" + FileDesc2 + " NINC=" + numberOfDS +
" QMAN=" + Qman + " QCOM=" + Qcomponent + " RMAN=" + RAMan + " EFACT=" + Experiance + " NPIN=" +
NumberOfPins + " TRCM=TRUSER TEMPR=" + RiseofTemp
, "FID-" + FileID, Environment.NewLine);
csv.Append(DataLine);
}
if (type == "Pi_PROCESS&Pi_PM&LIFE PROFILE")
{
newLine = string.Format(
"{0},{1},{2},{3},{4},{5},{6},{7},{9},{10},{11},{12},{13},{14},{15},{16},{17},{18},{19},{20},{21},{22},{23} {25}",
"AmbientTemp", "AppPollution", "CycleDuration", "DeltaTCycling", "Description", "EnvPollution", "HumanExposure", "MachineExposure", "MaxTCycling", "NetworkType", "NoCycles", "OnForPhase", "PhaseDuration", "ProductManip", "Project", "ProLevel","RandomVibs","RelHumidity","SalPollution", "SubIndex","SystemMobility","UserQual", "UserType","WeatherExposure", Environment.NewLine);
csv.Append(newLine);
}
}
File.WriteAllText(fileLoc, csv.ToString());
MessageBox.Show("File written to" + fileLoc);
}
private void btnGenerateImport_Click(object sender, EventArgs e)
{
Stream myStream = null;
SaveFileDialog CSVGen = new SaveFileDialog();
CSVGen.InitialDirectory = "C:''";
CSVGen.Filter = "CSV File (*.csv)|*.csv";
CSVGen.FilterIndex = 2;
CSVGen.RestoreDirectory = true;
CSVGen.ShowDialog();
string fileLoc = CSVGen.FileName;
GenerateCSV(fileLoc, cmbSheetSelect.Text);
}
}
}
你必须使用反射来实现这个
foreach(var sheetName in ExcelSheets)
{
var prop = this.GetType().GetField(sheetName, BindingFlags.NonPublic | BindingFlags.Instance);
prop.SetValue(this, dt.ReadFunction());
}
我在我的Form1构造函数中有以下内容,它为我工作。
private DataTable Version, Pi_PROCESSPi_PMLIFEPROFILE, PIAPPLICATION, PIRUGGEDISING, ELECTRONICCOMPONENT, HFANDRFCOMPONENTS, HYBRIDANDMULTICHIPMODULE, COTSBOARDS, VARIOUSSUBASSEMBLIES, PARTCOUNT, FAMILYCOUNT;
List<string> ExcelSheets = new List<string>();
public Form1()
{
InitializeComponent();
var list = new string[] { "Version", "Pi_PROCESSPi_PMLIFEPROFILE", "PIAPPLICATION", "PIRUGGEDISING", "ELECTRONICCOMPONENT", "HFANDRFCOMPONENTS", "HYBRIDANDMULTICHIPMODULE", "COTSBOARDS", "VARIOUSSUBASSEMBLIES", "PARTCOUNT", "FAMILYCOUNT" };
ExcelSheets= list.ToList();
foreach(var sheet in ExcelSheets)
{
var prop = this.GetType().GetField(sheet, BindingFlags.NonPublic | BindingFlags.Instance);
Debug.WriteLine(prop.FieldType);
Debug.WriteLine(prop != null);
}
}