-1
Я строю страницу для извлечения данных SQL в листы шаблонов Excel. Я запускаю исключение «Данный ключ не присутствовал в словаре». При отладке, он указывает наC# экспорт SQL в Excel шаблоны
public void AddField(string Column, dynamic Value)
{
AddField(_KeyList[Column.ToUpper()], Value);
}
часть "ExcelExport.cs"
Вот мой "ExcelExport.cs" код
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using OfficeOpenXml;
using System.IO;
using System.Reflection;
namespace ScanPortal
{
public class ExcelExport
{
private FileInfo _TemplateFile;
private int _StartRow;
private int _CurrentRow;
private Dictionary<int, Dictionary<int, string>> _ValueGrid;
private Dictionary<string, int> _KeyList;
private Dictionary<int, int> _InsertList;
public ExcelExport(string Template = "", int StartRowIndex = 1, int KeyRow = 0)
{
if (Template != "")
{
_TemplateFile = new FileInfo(Template);
}
_InsertList = new Dictionary<int, int>();
if (KeyRow > 0)
{
using (var package = new ExcelPackage(_TemplateFile))
{
_KeyList = new Dictionary<string, int>();
ExcelWorksheet worksheet = package.Workbook.Worksheets.First();
int ColIndex = 1;
int NumBlank = 0;
do
{
object Value = worksheet.Cells[KeyRow, ColIndex].Value;
if (Value == null) { NumBlank++; ColIndex++; continue; }
NumBlank = 0;
_KeyList.Add(Value.ToString().ToUpper(), ColIndex);
ColIndex++;
} while (NumBlank < 5);
}
}
_StartRow = StartRowIndex;
_CurrentRow = _StartRow;
_ValueGrid = new Dictionary<int, Dictionary<int, string>>();
_ValueGrid.Add(_StartRow, new Dictionary<int, string>());
}
public void AddField(int Row, int Column, dynamic Value)
{
if (Column < 1 || Row < 1) throw new IndexOutOfRangeException();
if (Value == null) Value = "";
if (!_ValueGrid.ContainsKey(_CurrentRow))
{
_ValueGrid.Add(Row, new Dictionary<int, string>());
}
_ValueGrid[Row].Add(Column, Value.ToString());
}
public void AddField(string Column, dynamic Value)
{
AddField(_KeyList[Column.ToUpper()], Value);
}
public void AddField(int Column, dynamic Value)
{
if (Column < 1) throw new System.IndexOutOfRangeException();
if (Value == null) Value = "";
_ValueGrid[_CurrentRow].Add(Column, Value.ToString());
}
public void NextRow()
{
_CurrentRow++;
_ValueGrid.Add(_CurrentRow, new Dictionary<int, string>());
}
public void InsertRow(int count = 1)
{
_CurrentRow++;
_ValueGrid.Add(_CurrentRow, new Dictionary<int, string>());
_InsertList.Add(_CurrentRow, count);
}
public bool GenerateWorkbook(string FileName, bool DownloadSheet = true)
{
if (!FileName.ToUpper().Contains(".XLSX"))
{
FileName += ".xlsx";
}
using (ExcelPackage pck = (_TemplateFile != null ? new ExcelPackage(_TemplateFile, true) : new ExcelPackage()))
{
ExcelWorksheet ws = pck.Workbook.Worksheets[1];
foreach (var DictRow in _ValueGrid)
{
int RowIndex = DictRow.Key;
if (_InsertList.ContainsKey(RowIndex))
{
ws.InsertRow(RowIndex, _InsertList[RowIndex]);
}
foreach (var DictColumn in DictRow.Value)
{
int ColumnIndex = DictColumn.Key;
string ColumnValue = DictColumn.Value;
ws.Cells[RowIndex, ColumnIndex].LoadFromText(ColumnValue);
}
}
if (DownloadSheet)
{
HttpResponse Response = System.Web.HttpContext.Current.Response;
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=" + FileName);
Response.BinaryWrite(pck.GetAsByteArray());
Response.End();
}
}
return true;
}
}
}
Вот мой «ExportReports.aspx. cs "
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using OfficeOpenXml;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace ScanPortal
{
public partial class ExportReports : System.Web.UI.Page
{
Dictionary<int, string> DropDowns;
protected void btnVisitation_Click(object sender, EventArgs e)
{
ExcelExport excel = new ExcelExport(Server.MapPath("JSPRC Visit Summary Data Template.xlsx"), 3, 2);
using (var db = new FormsDataContext())
{
excel.AddField("agency", "SCAN");
}
excel.GenerateWorkbook("Visit Summary Data");
}
}
}
Какую строку в коде вы получаете эту конкретную ошибку ..? fyi эта ошибка обычно возникает, когда вы пытаетесь получить доступ к ключу, которого там нет. – MethodMan
строка 70 на ExcelExport.cs Как я могу получить ключ там в этом случае? –
Ну, какие ключи вы используете для индексации своего словаря? Готов поспорить, что ключ не найден. –