日期:2014-05-18  浏览次数:20761 次

大吓我的程序是在winfrom下的不是在WEB下!!我在一个窗口中有一个datagrid 用户点一边上的按钮就可以将datagrid里的数据导出到laoye.xls我要怎么写啊?求!!
大吓我的程序是在winfrom下的不是在WEB下!!我在一个窗口中有一个datagrid 用户点一边上的按钮就可以将datagrid里的数据导出到laoye.xls我要怎么写啊?求!! 
 另外请各位大虾 把引用空间写明!! 多谢了!

------解决方案--------------------
这个是 this.datagridview导出的
引用COM组建的Microsoft.Office.Excel

 Microsoft.Office.Interop.Excel.Application appExcel;

appExcel = new Microsoft.Office.Interop.Excel.Application();
Workbook workbookData;
Worksheet worksheetData;

appExcel.Visible = true;

// set culture to US
System.Globalization.CultureInfo CurrentCI = System.Threading.Thread.CurrentThread.CurrentCulture;
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");


workbookData = appExcel.Workbooks.Add(Missing.Value);

worksheetData = (Worksheet)workbookData.Worksheets.Add(Missing.Value, Missing.Value, Missing.Value, Missing.Value);
worksheetData.Name = "Saved";

for (int i = 0; i < this.datagridview1.Columns.Count; i++)
{
worksheetData.Cells[1, i + 1] = this.datagridview1.Columns[i].HeaderText;
}


Range xlRang = null;
int iRowCount = dt.Rows.Count;
int iParstedRow = 0, iCurrSize = 0;
int iEachSize = 1000;
int iColumnAccount = dt.Columns.Count;
int iCurrentRow = 0;
int iSheet = 1;

object[,] objVal = new object[iEachSize, iColumnAccount];

try
{
iCurrSize = iEachSize;
while (iParstedRow < iRowCount)
{
if ((iRowCount - iParstedRow) < iEachSize)
iCurrSize = iRowCount - iParstedRow;

for (int i = 0; i < iCurrSize; i++)
{
for (int j = 0; j < iColumnAccount; j++)
objVal[i, j] = dt.Rows[iParstedRow + i][j].ToString();
}
xlRang = worksheetData.get_Range("A" + ((int)(iCurrentRow + 2)).ToString(), ((char)('A' + iColumnAccount - 1)).ToString() + ((int)(iCurrentRow + iCurrSize + 1)).ToString());

xlRang.Value2 = objVal;
iParstedRow = iParstedRow + iCurrSize;
iCurrentRow = iCurrentRow + iCurrSize;
if (iCurrentRow > 6500)
{
worksheetData = (Worksheet)workbookData.Worksheets.Add(Type.Missing, workbookData.Worksheets.get_Item(iSheet), Type.Missing, Type.Missing);
iSheet += 1;
for (int i = 0; i < this.datagridview1.Columns.Count; i++)
{
worksheetData.Cells[1, i + 1] = this.datagridview1.Columns[i].HeaderText;
}
iCurrentRow = 0;
}
}

System.Runtime.InteropServices.Marshal.ReleaseComObject(xlRang);
xlRang = null;

}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
// return to previous culture
System.Threading.Thread.CurrentThread.CurrentCulture = CurrentCI;