vb.net
Dim sfDialog As SaveFileDialog = New SaveFileDialog()
sfDialog.FileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls"
sfDialog.Filter = "xls | *.xls"
Dim app As Microsoft.Office.Interop.Excel.Application = New Microsoft.Office.Interop.Excel.Application()
If sfDialog.ShowDialog() = DialogResult.OK Then
Try
Dim wBooks As Microsoft.Office.Interop.Excel.Workbooks = app.Workbooks
Dim wBook As Microsoft.Office.Interop.Excel.Workbook = wBooks.Add(True)
Dim wSheet As Microsoft.Office.Interop.Excel.Worksheet = wBook.ActiveSheet
Dim dt As DataTable = New DataTable()
dt.Columns.Add("ID")
Dim dr As DataRow = dt.NewRow()
dr(0) = "asdf"
dt.Rows.Add(dr)
For index = 0 To dt.Rows.Count - 1
wSheet.Cells(index + 1,index + 1) = dt.Rows(index)(index)
Next
wBook.SaveAs(sfDialog.FileName,Microsoft.Office.Interop.Excel.XlFileFormat.xlExcel9795,
Nothing,Nothing,False,Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive,Nothing)
wBook.Close(True,Nothing)
System.Runtime.InteropServices.Marshal.ReleaseComObject(wSheet)
System.Runtime.InteropServices.Marshal.ReleaseComObject(wBook)
System.Runtime.InteropServices.Marshal.ReleaseComObject(app)
wSheet = Nothing
wBook = Nothing
app = Nothing
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End If
C#.net
SaveFileDialog sfDialog = new SaveFileDialog();
sfDialog.FileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
sfDialog.Filter = "xls | *.xls";
if (sfDialog.ShowDialog() == DialogResult.OK)
{
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
try
{
object MissingValue = Type.Missing;
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
wbs = app.Workbooks;
wb = wbs.Add(true);
Microsoft.Office.Interop.Excel.Worksheet wsheet = wb.ActiveSheet as Microsoft.Office.Interop.Excel.Worksheet;
DataTable dt = new DataTable();
dt.Columns.Add("ID");
DataRow dr = dt.NewRow();
dr[0] = "dfasad";
dt.Rows.Add(dr);
for (int i = 0; i < dt.Columns.Count; i++)
{
//注意下面是i+1,excel小标默认从1开始
wsheet.Cells[1,i + 1] = dt.Rows[i][i];
}
wb.SaveAs(sfDialog.FileName,null,false,false
,null);
wb.Close(true,null);
System.Runtime.InteropServices.Marshal.ReleaseComObject(wsheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(wb);
System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
wsheet = null;
wb = null;
app = null;
}
catch (Exception e1)
{
MessageBox.Show("出现错误:" + e1.Message);
} finally { excel.Quit(); excel = null; } }