我正在开发一个C#项目,该项目将用于读取excel电子表格中的值,清理值以确保数据正确,然后将所述值插入数据库表中。话虽如此,我对C#也是相当新的(这是我的第一个“大”项目“),所以在同事的帮助下,我们在编码的三个要求中有两个。
有了这个背景,我无法调用存储了值的类,因此我可以将它们插入到所需的表中。这是我到目前为止的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;
using System.Text.RegularExpressions;
namespace ReadExcel
{
public partial class Form1 : Form
{
public Microsoft.Office.Interop.Excel._Application excelApp = new Microsoft.Office.Interop.Excel.Application() { DisplayAlerts = false, Visible = false };
public List<Attorney> listOfAttys = Helpers.getAttorneys();
public List<LegalTransactionRec> listofTransactions = Helpers.insertRecords();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
setAttyList();
}
private void setAttyList()
{
foreach (var item in listOfAttys.Select(x => x.Caption))
cmbAtty.Items.Add(item);
}
public void btnRun_Click(object sender, EventArgs e)
{
Workbook workbook = excelApp.Workbooks.Open(txtbxFilename.Text);
try
{
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets.get_Item(1);
Microsoft.Office.Interop.Excel.Range xlRange = worksheet.UsedRange;
int rowCount = xlRange.Rows.Count;
int colCount = xlRange.Columns.Count;
List<LegalTransactionRec> lstTran = new List<LegalTransactionRec>();
for (int i = 1; i <= rowCount; i++)
{
for (int j = 1; j <= colCount; j++)
{
lstTran.Add(new LegalTransactionRec()
{
AccountNumber = CleanString(xlRange.Cells[i, 1].Value2.ToString()),
CostAmount = TryToParse(CleanAmount(xlRange.Cells[i, 3].Value2.ToString())),
SSN = CleanString(xlRange.Cells[i, 6].Value2.ToString()),
TransactionDate = CheckDate(xlRange.Cells[i, 2].Value2.ToDate()),
Description = xlRange.Cells[i, 8].Value2.ToString(),
TransactionCode = CheckNull(xlRange.Cells[i, 2].Value2.ToInt())
});
}
}
if (validateHeader(worksheet))
{
}
}
catch (Exception ex)
{
}
excelApp.Quit();
}
private void btnLoad_Click(object sender, EventArgs e)
{
txtbxFilename.Text = null;
System.IO.Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "C:\\";
openFileDialog1.Filter = "Excel files (*.xlsx)|*.xlsx";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
txtbxFilename.Text = openFileDialog1.FileName;
myStream.Close();
myStream.Dispose();
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}
private bool validateHeader(Microsoft.Office.Interop.Excel.Worksheet Worksheet)
{
if (Worksheet == null)
return false;
bool isValid = false;
//get header row
//check all cell values
return isValid;
}
public int CheckNull(int intVal)
{
int cleanValue;
if (intVal == null)
{
throw new System.ArgumentException("Value cannot be null", "original");
}
else
{
cleanValue = intVal;
}
return cleanValue;
}
public string CleanString(String strVal)
{
string cleanValue;
if (strVal == null)
{
throw new System.ArgumentException("Value cannot be null", "original");
}
else
{
cleanValue = Regex.Replace(strVal," ", "").Replace("$","").Replace("-","");
}
return cleanValue;
}
public string CleanAmount(String amt)
{
string cleanAmt;
if (amt == null)
{
throw new System.ArgumentException("Value cannot be null", "original");
}
else
{
cleanAmt = Regex.Replace(amt, "(", "-").Replace(")", "").Replace("$","").Replace("[^0-9]+", "").Replace(" ","");
}
return cleanAmt;
}
public static void TryToParse(string strAmt)
{
decimal decAmt;
bool result = Decimal.TryParse(strAmt, out decAmt);
}
public DateTime CheckDate(DateTime tranDate)
{
DateTime date;
if (tranDate == null)
{
throw new System.ArgumentException("Value cannot be null", "original");
}
else
{
date = tranDate;
}
return date;
}
}
public class Attorney
{
public string AttorneyID { get; set; }
public int OrganizationID { get; set; }
public string AttorneyName { get; set; }
public string Caption { get; set; }
}
public class LegalTransactionRec
{
public string AccountNumber { get; set; }
public string CostAmount { get; set; }
public string SSN { get; set; }
public int BatchID { get; set; }
public Attorney Attorney { get; set; }
public DateTime TransactionDate { get; set; }
public string Description { get; set; }
public int TransactionCode { get; set; }
}
public class ReviewOutput
{
}
public class ApprovedOutput
{
}
}
这是另一部分:
编辑:我在插入语句开始之前添加了一些代码,我想我可能能够像创建select statement
时使用的同事一样使用DataRows。我现在的问题只是弄清楚如何指向我的类,其中包含我需要插入的值。
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ReadExcel
{
class Helpers
{
public static List<Attorney> getAttorneys()
{
List<Attorney> lst = new List<Attorney>();
StringBuilder sql = new StringBuilder();
sql.AppendLine("SELECT ");
sql.AppendLine(" V.ATTORNEY_ID, V.ORGANIZATION_ID, A.NAME, ( '(' || V.ATTORNEY_ID || ') - ' || a.name ) as caption");
sql.AppendLine("FROM ");
sql.AppendLine(" VENDOR_PORTAL.organization_attys V, ATLAS.RLGLENTY A ");
sql.AppendLine("WHERE ");
sql.AppendLine(" V.ATTORNEY_ID = A.ID_CODE (+) ");
sql.AppendLine(" and V.organization_id != 122 ");
sql.AppendLine(" and V.organization_id is not null ");
sql.AppendLine("ORDER BY A.NAME ASC ");
using (DataTable dt = DataManager.GetData(sql))
{
foreach (DataRow dr in dt.Rows)
{
try
{
lst.Add(new Attorney()
{
AttorneyName = dr["name"].Equals(DBNull.Value) ? "" : dr["name"].ToString(),
OrganizationID = int.Parse(dr["organization_id"].ToString()),
AttorneyID = dr["attorney_id"].Equals(DBNull.Value) ? "" : dr["attorney_id"].ToString(),
Caption = dr["caption"].Equals(DBNull.Value) ? "" : dr["caption"].ToString()
});
}
catch (Exception ex)
{ }
}
}
return lst;
}
public static List<LegalTransactionRec> insertRecords()
{
StringBuilder sql = new StringBuilder();
using (DataTable dt = DataManager.GetData(sql))
{
foreach (DataRow dr in dt.Rows)
{
try
{
sql.AppendLine("INSERT INTO PCOSCETTE.LEGAL_TRANSCATIONS (BATCH_ID, ACCOUNT, ATTORNEY_ID, ORG_ID, TRANSACTION_DATE, DATE_INSERTED, TRANSACTION_CODE, AMOUNT, DESCRIPTION, DEBTOR_SSN");
sql.AppendLine("VALUES ( (select max(batch_id) from pcoscette.legal_transaction_batch_info),");
}
catch (Exception ex)
{ }
}
}
}
}
}
正确方向的任何一点都将是一个救生员,谢谢。如果我忘记了原帖中的任何内容,请告诉我,我会添加它。
答案 0 :(得分:0)
创建Class
的实例,并使用values
分配所需的class properties
或变量
以下是您的代码的一个小示例。
你的班级 -
public class LegalTransactionRec
{
public string AccountNumber { get; set; }
public string CostAmount { get; set; }
public string SSN { get; set; }
public int BatchID { get; set; }
public Attorney Attorney { get; set; }
public DateTime TransactionDate { get; set; }
public string Description { get; set; }
public int TransactionCode { get; set; }
}
创建班级实例;
LegalTransactionRec objLegal= new LegalTransactionRec(); //objLegal is instance name you can name it as you want
为您的类属性指定值。
objLegal.AccountNumber= someValue1 // or variable
objLegal.CostAmount= someValue2 // or variable
........