运行时代码中红色部分提示为“未将对象引用设置到对象的实例”
代码如下: public bool ExportDataGridview(DataGridView gridView, bool isShowExcle)
{
if (gridView.Rows.Count == 0)
return false;
//建立Excel对象
//Microsoft.Office.Tools.Excel.ec
Excel.Application excel = new Excel.Application();
excel.Application.Workbooks.Add(true);
excel.Visible = isShowExcle;
//生成字段名称
for (int i = 0; i < gridView.ColumnCount; i++)
{
excel.Cells[1, i + 1] = gridView.Columns[i].HeaderText;
}
//填充数据
for (int i = 0; i < gridView.RowCount - 1; i++)
{
for (int j = 0; j < gridView.ColumnCount; j++)
{
if (gridView.Rows[i].Cells[j].ValueType == typeof(string))
{
excel.Cells[i + 2, j + 1] = "'" + gridView.Rows[i].Cells[j].Value.ToString();
}
else
{
excel.Cells[i + 2, j + 1] = gridView.Rows[i].Cells[j].Value.ToString();
}
}
}
return true;
}
代码如下: public bool ExportDataGridview(DataGridView gridView, bool isShowExcle)
{
if (gridView.Rows.Count == 0)
return false;
//建立Excel对象
//Microsoft.Office.Tools.Excel.ec
Excel.Application excel = new Excel.Application();
excel.Application.Workbooks.Add(true);
excel.Visible = isShowExcle;
//生成字段名称
for (int i = 0; i < gridView.ColumnCount; i++)
{
excel.Cells[1, i + 1] = gridView.Columns[i].HeaderText;
}
//填充数据
for (int i = 0; i < gridView.RowCount - 1; i++)
{
for (int j = 0; j < gridView.ColumnCount; j++)
{
if (gridView.Rows[i].Cells[j].ValueType == typeof(string))
{
excel.Cells[i + 2, j + 1] = "'" + gridView.Rows[i].Cells[j].Value.ToString();
}
else
{
excel.Cells[i + 2, j + 1] = gridView.Rows[i].Cells[j].Value.ToString();
}
}
}
return true;
}
{
Response.Clear();
Response.Charset = "gb2312;";
Response.ContentType = "application/vnd.ms-excel";
System.IO.StringWriter oSW = new System.IO.StringWriter();
HtmlTextWriter oHW = new HtmlTextWriter(oSW);
DataGrid oDG = new DataGrid();
oDG.DataSource = oDS;
oDG.DataBind();
oDG.RenderControl(oHW);
//OrderGridView.RenderControl(oHW);
Response.Write(oSW.ToString());
Response.Flush();
Response.Close();
}
用这个吧
{
excel.Cells[i + 2, j + 1] = gridView.Rows[i].Cells[j].Value.ToString();
}
if(gridView.Rows[i].Cells[j].Value!=null)
{
excel.Cells[i + 2, j + 1] = gridView.Rows[i].Cells[j].Value.ToString();
}
但还是报一样的错!
//建议根据数据源(DataSource)去导出
foreach (DataRow row in myRow)
{
colIndex = 0; foreach (DataColumn col in dt.Columns)
{
colIndex++;
try
{
if (col.DataType == System.Type.GetType("System.DateTime"))
{
dataRowList[i, j] = (Convert.ToDateTime(row[col.ColumnName].ToString())).ToString("yyyy-MM-dd"); }
else if (col.DataType == System.Type.GetType("System.String"))
{
dataRowList[i, j] = "'" + row[col.ColumnName].ToString();
}
else
{
dataRowList[i, j] = row[col.ColumnName].ToString();
}
}
catch
{
dataRowList[i, j] = "1900-01-01";
}
j++;
}
if(DataGrieView.Rows.count==0)
return;