对,这开始让我发疯,我有一个带有复选框的 asp:gridview,用户可以检查他/她想要导出到 excel 的哪些信息,当他们单击按钮时,执行下面的代码,现在你可以看到我在 gridview 等中为每一行做一个
如果选中了一行的复选框,我会去数据库执行一些信息,返回一个数据表,然后尝试将其值添加到 Epplus excel 电子表格中,但foreach(datacolum)
它foreach(DataRow)
不允许我使用
ws.Cells[1, iColumnCount] = c.ColumnName; as it says its read only?
但是这个excel电子表格可能有1-10个不同的信息位,具体取决于检查了多少个复选框......有人可以帮助我,让我摆脱痛苦...... :(
这是我的完整代码
protected void BtnTest_Click(object sender, EventArgs e)
{
bool ReportGenerated = false;
FileInfo newFile = new FileInfo("C:\\Users\\Scott.Atkinson\\Desktop\\book1.xls");
ExcelPackage pck = new ExcelPackage(newFile);
foreach (GridViewRow row in gvPerformanceResult.Rows)
{
object misValue = System.Reflection.Missing.Value;
CheckBox chkExcel = (CheckBox)row.FindControl("chkExportToExcel");
if (chkExcel.Checked)
{
HyperLink HypCreatedBy = (HyperLink)row.FindControl("HyperCreatedBy"); //Find the name of Sales agent
string CreatedBy = HypCreatedBy.Text;
string Fname = HypCreatedBy.Text;
string[] names = Fname.Split();
CreatedBy = names[0];
CreatedBy = CreatedBy + "." + names[1];
WebUser objUser = new WebUser(CreatedBy, true);
DataTable DT = new DataTable();
LeadOpportunities objLeadOpportunities = new LeadOpportunities();
DT = objLeadOpportunities.LoadPRCDetail("PRC", objUser.ShortAbbr, objUser.CanViewAllLead, ReportCriteria); // Load the information to export to Excel.
if (DT.Rows.Count > 0)
{
ReportGenerated = true;
//Add the Content sheet
var ws = pck.Workbook.Worksheets.Add("Content");
ws.View.ShowGridLines = true;
int iRowCount = ws.Dimension.Start.Row; //Counts how many rows have been used in the Excel Spreadsheet
int iColumnCount = ws.Dimension.Start.Column; //Counts how many Columns have been used.
if (iRowCount > 1)
iRowCount = iRowCount + 2;
else
iRowCount = 1;
iColumnCount = 0;
foreach (DataColumn c in DT.Columns)
{
iColumnCount++;
if (iRowCount == 0)
ws.Cells[1, iColumnCount] = c.ColumnName;
else
ws.Cells[iRowCount, iColumnCount] = c.ColumnName;
}
foreach (DataRow r in DT.Rows)
{
iRowCount++;
iColumnCount = 0;
foreach (DataColumn c in DT.Columns)
{
iColumnCount++;
if (iRowCount == 1)
ws.Cells[iRowCount + 1, iColumnCount] = r[c.ColumnName].ToString();
else
ws.Cells[iRowCount, iColumnCount] = r[c.ColumnName].ToString();
WorkSheet.Columns.AutoFit(); //Correct the width of the columns
}
}
pck.Save();
System.Diagnostics.Process.Start("C:\\Users\\Scott.Atkinson\\Desktop\\book1.xls");
}
}
}
}
任何帮助将不胜感激。