1つのデータテーブル(facilData)と別のデータテーブル(ownerData)のデータを取得し、別のデータテーブル(dataStore)に書き込もうとしています。 2番目は最初のものと同じではありません。以下のコードを試してみましたが、次のエラーが表示されます。"System.StringとSystem.Stringの型が一致しません"。次に、デバッガが私を取り戻し、下のコードで(int)table2 ["rowIndex"]をハイライト表示します。joinステートメントを使用して2つの異なるデータセットからC#で1つにデータをリンクする
public void Write2Sheet(DataTable dt1, DataTable dt2, DataTable dt3, String newFilePath)
{
try
{
//Merge the three Datatables into the single Datatable source
var mdata = from table1 in facilData.AsEnumerable()
join table2 in ownerData.AsEnumerable() on (int)table1["rowIndex"] equals (int)table2["rowIndex"]
select new
{
rowIndex = (int)table1["rowIndex"],
Prog = (string)table1["Prog"],
cStatus = (string)table1["cStatus"],
bStatus = (string)table1["bStatus"],
fID = (string)table1["fID"],
fNam = (string)table1["fNam"],
fAdd = (string)table1["fAdd"],
fCity = (string)table1["fCity"],
fState = (string)table1["fState"],
fCode = (string)table1["fCode"],
oInfo = (string)table2["oInfo"],
pgRecId = (string)table1["pgRecId"],
lAct = (string)table1["lAct"]
};
foreach (var rec in mdata)
{
var row = dataStore.NewRow();
row["rowIndex"] = rec.rowIndex;
row["Prog"] = rec.Prog;
row["cStatus"] = rec.cStatus;
row["bStatus"] = rec.bStatus;
row["fID"] = rec.fID;
row["fNam"] = rec.fNam;
row["fAdd"] = rec.fAdd;
row["fCity"] = rec.fCity;
row["fState"] = rec.fState;
row["fCode"] = rec.fCode;
row["oInfo"] = rec.oInfo;
row["pgRecId"] = rec.pgRecId;
row["lAct"] = rec.lAct;
dataStore.Rows.Add(row);
}
}
catch (Exception e)
{
Write2LogFile("The data tables couldn't merge because: " + e.Message);
}
//Write from the Datatable source to the new spreadsheet and save it
try
{
FileInfo newSheet = new FileInfo(fileName);
using (ExcelPackage xPkg = new ExcelPackage(newSheet))
{
ExcelWorksheet worksheet = xPkg.Workbook.Worksheets[1];
var cell = worksheet.Cells;
int rI = 2;
foreach (DataRow dr in dataStore.Rows)
{
string iDX = rI.ToString();
worksheet.Cells["A" + iDX].Value = dr["Prog"].ToString();
worksheet.Cells["B" + iDX].Value = dr["cStatus"].ToString();
worksheet.Cells["C" + iDX].Value = dr["bStatus"].ToString();
worksheet.Cells["D" + iDX].Value = dr["fID"].ToString();
worksheet.Cells["E" + iDX].Value = dr["fNam"].ToString();
worksheet.Cells["F" + iDX].Value = dr["fAdd"].ToString();
worksheet.Cells["G" + iDX].Value = dr["fCity"].ToString();
worksheet.Cells["H" + iDX].Value = dr["fState"].ToString();
worksheet.Cells["I" + iDX].Value = dr["fCode"].ToString();
worksheet.Cells["J" + iDX].Value = dr["oInfo"].ToString();
worksheet.Cells["K" + iDX].Value = dr["pgRecId"].ToString();
worksheet.Cells["L" + iDX].Value = dr["lAct"].ToString();
rI++;
}
xPkg.Save();
}
}
catch (Exception ex)
{
Write2LogFile("Data was not written to spreadsheet because: " + ex.Message);
}
}
DBNullにキャストしようとすると、**(int?)**の代わりに**(int?)**を使用しようとしましたか?作業しないでください... table1とtable2はどこに定義されていますか? (facilData、ownerData) –
rowIndexがfacilDataとownerDataの両方に値を持っていることを確認しましたか? – Massanu
値がnullまたは空の場合は、DBNull.valueを渡します。 –