我将gridview数据导出到excel但不幸的是导出文件中的数据不同,应该是数据表。
下面是我在导出按钮中的脚本,你能告诉我我的脚本有什么问题吗?我是ASP.net的新人,谢谢
try
{
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
excel.Visible = true;
Microsoft.Office.Interop.Excel.Workbook workbook = excel.Workbooks.Add(System.Reflection.Missing.Value);
Microsoft.Office.Interop.Excel.Worksheet sheet1 = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets[1];
int StartCol = 1;
int StartRow = 1;
int j = 0, i = 0;
//Write Headers
for (j = 0; j < GridView1.Columns.Count; j++)
{
Microsoft.Office.Interop.Excel.Range myRange = (Microsoft.Office.Interop.Excel.Range)sheet1.Cells[StartRow, StartCol + j];
myRange.Value = GridView1.Columns[j].HeaderText;
}
StartRow++;
//Write datagridview content
for (i = 0; i < GridView1.Rows.Count; i++)
{
for (j = 0; j < GridView1.Columns.Count; j++)
{
try
{
Microsoft.Office.Interop.Excel.Range myRange = (Microsoft.Office.Interop.Excel.Range)sheet1.Cells[StartRow + i, StartCol + j];
myRange.Value2 = GridView1.Rows[i].Cells[j].Text + ";" == null ? "" : GridView1.Rows[i].Cells[j].Text + ";";
}
catch
{
GridView1.DataBind();
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
// ScriptManager.RegisterClientScriptBlock(this, this.GetType(),
// "alertMessage",
// "alert(ex.ToString());", true);
}
答案 0 :(得分:0)
您可以使用以下方法将datagridview数据导出到Excel:
public void ExportToExcel(DataGridView dgv)
{
try
{
dgv.SelectAll();
dgv.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText;
DataObject doj = dgv.GetClipboardContent();
Clipboard.SetDataObject(doj);
dgv.ClearSelection();
Microsoft.Office.Interop.Excel.Application exap = new Microsoft.Office.Interop.Excel.Application();
exap.Visible = true;
Workbook exwb = (Workbook)exap.Workbooks.Add();
Worksheet exws = (Worksheet)exwb.Sheets["Sheet1"];
exws.Paste();
Clipboard.Clear();
Range cell1 = exws.Cells[1, 2];
Range cell2 = exws.Cells[dgv.Rows.Count + 1, dgv.ColumnCount + 1];
Range cell3 = exws.Cells[1, dgv.ColumnCount + 1];
Range range = exws.get_Range(cell1, cell2);
Range colorrange = exws.get_Range(cell1, cell3);
range.Borders.Weight = XlBorderWeight.xlThin;
colorrange.Interior.Color = System.Drawing.Color.SteelBlue;
colorrange.Font.Color = System.Drawing.Color.White;
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Excel File 2010 (*.xlsx)|*.xlsx|Excel File 2003 (*.xls)|*.xls";
if (sfd.ShowDialog() == DialogResult.OK)
{
exwb.SaveAs(sfd.FileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
}
}
catch(System.Exception ex)
{
MessageBox.Show(ex.Message);
}
}
此方法复制datagridview&amp;中的所有数据。将它粘贴到excel中。您需要添加对Microsoft.Office.Interop.Excel的引用。
或者,如果您希望将数据表导出到Excel,可以尝试以下方法:
public void ExporttoExcel(System.Data.DataTable dtbl)
{
StringBuilder Output = new StringBuilder();
//The first "line" will be the Headers.
for (int i = 0; i < dtbl.Columns.Count; i++)
{
Output.Append(dtbl.Columns[i].ColumnName + "\t");
}
Output.Append("\n");
//Generate Cell Value Data
foreach (DataRow Row in dtbl.Rows)
{
if (Row.RowState != DataRowState.Deleted)
{
for (int i = 0; i < Row.ItemArray.Length; i++)
{
//Handling the last cell of the line.
if (i == (Row.ItemArray.Length - 1))
{
Output.Append(Row.ItemArray[i].ToString() + "\n");
}
else
{
Output.Append(Row.ItemArray[i].ToString() + "\t");
}
}
}
}
Clipboard.SetText(Output.ToString());
Microsoft.Office.Interop.Excel.Application exap = new Microsoft.Office.Interop.Excel.Application();
exap.Visible = true;
Workbook exwb = (Workbook)exap.Workbooks.Add();
Worksheet exws = (Worksheet)exwb.Sheets["Sheet1"];
exws.Paste();
Clipboard.Clear();
Range cell1 = exws.Cells[1, 1];
Range cell2 = exws.Cells[dtbl.Rows.Count, dtbl.Columns.Count];
Range cell3 = exws.Cells[1, dtbl.Columns.Count];
Range range = exws.get_Range(cell1, cell2);
Range colorrange = exws.get_Range(cell1, cell3);
range.Borders.Weight = XlBorderWeight.xlThin;
colorrange.Interior.Color = System.Drawing.Color.SteelBlue;
colorrange.Font.Color = System.Drawing.Color.White;
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Excel File 2010 (*.xlsx)|*.xlsx|Excel File 2003 (*.xls)|*.xls";
if (sfd.ShowDialog() == DialogResult.OK)
{
exwb.SaveAs(sfd.FileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
}
}
请检查这些方法是否有帮助。
答案 1 :(得分:0)
使用Text.Replace(" ", "")
myRange.Value2 = GridView1.Rows[i].Cells[j].Text.Replace(" ", "") + ";" == null ? "" : GridView1.Rows[i].Cells[j].Text + ";";
标记中的
<asp:BoundField DataField="EmployeeName" HeaderText="Name" NullDisplayText=" "/>
答案 2 :(得分:0)
我怀疑你的GridView Bind失败了。以下是您可以尝试的方法。
private void ExportToExcel()
{
//First fetch all records from grid to dataset
DataSet dset = new DataSet();
dset.Tables.Add();
//First Add Columns from gridview to excel
for (int i = 0; i < gridView.Columns.Count; i++) //GridView is id of gridview
{
dset.Tables[0].Columns.Add(gridView.Columns[i].HeaderText);
}
//add rows to the table
System.Data.DataRow dr1;
for (int i = 0; i < gridView.Rows.Count; i++)
{
dr1 = dset.Tables[0].NewRow(); //For Example There are only 3 columns into gridview
System.Web.UI.WebControls.Label lblCCName =
(System.Web.UI.WebControls.Label)gridView.Rows[i].Cells[0].FindControl("lblCCName");
System.Web.UI.WebControls.Label lblItemName =
(System.Web.UI.WebControls.Label)gridView.Rows[i].Cells[0].FindControl("lblItemName");
System.Web.UI.WebControls.Label lblItemCode =
(System.Web.UI.WebControls.Label)gridView.Rows[i].Cells[0].FindControl("lblItemCode");
dr1[0] = lblCCName.Text.ToString();
dr1[1] = lblItemName.Text.ToString();
dr1[2] = lblItemCode.Text.ToString();
dset.Tables[0].Rows.Add(dr1);
}
//below code is export dset to excel
ApplicationClass excel = new ApplicationClass();
Workbook wBook;
Worksheet wSheet;
wBook = excel.Workbooks.Add(System.Reflection.Missing.Value);
wSheet = (Worksheet)wBook.ActiveSheet;
System.Data.DataTable dt = dset.Tables[0];
System.Data.DataColumn dc = new DataColumn();
int colIndex = 0;
int rowIndex = 4;
foreach (DataColumn dcol in dt.Columns)
{
colIndex = colIndex + 1;
excel.Cells[5, colIndex] = dcol.ColumnName;
}
foreach (DataRow drow in dt.Rows)
{
rowIndex = rowIndex + 1;
colIndex = 0;
foreach (DataColumn dcol in dt.Columns)
{
colIndex = colIndex + 1;
excel.Cells[rowIndex + 1, colIndex] = drow[dcol.ColumnName];
}
}
wSheet.Columns.AutoFit();
// Server File Path Where you want to save excel file.
String strFileName = Server.MapPath("~\\Images\\StockStatement.xls");
Boolean blnFileOpen = false;
try
{
System.IO.FileStream fileTemp = File.OpenWrite(strFileName);
fileTemp.Close();
}
catch
{
blnFileOpen = false;
}
if (System.IO.File.Exists(strFileName))
//It checks if file exists then it delete that file.
{
System.IO.File.Delete(strFileName);
}
}
在Button_Click()
事件中,调用此函数。
答案 3 :(得分:0)
嗨,这是我长途旅行后出现的,我在Excel中使用Aspose方法导出Gridview,它简单但功能强大!希望这会有所帮助,
Export_button背后的代码:
//Instantiate a new workbook
Aspose.Cells.Workbook workbook = new Aspose.Cells.Workbook();
//Get the first worksheet in the workbook
Aspose.Cells.Worksheet worksheet = workbook.Worksheets[0];
//Import data from GridView control to fill the worksheet
worksheet.Cells.ImportGridView(GridView1, 0, 0, new Aspose.Cells.ImportTableOptions() { IsFieldNameShown = true });
worksheet.AutoFitColumns();
//Send result to client in XLS format
workbook.Save(this.Response, "export.xls", ContentDisposition.Attachment, new Aspose.Cells.XlsSaveOptions());