office 2003 可以直接导入

解决方案 »

  1.   

    这是我从excel导入sqlserver的代码,你改一下反过来就可以了。
    public  DataSet GetData(string filename)
    {

    string strConn;
    DataSet importData=new DataSet();
    strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +
    "Data Source="+filename+";"+
    "Extended Properties=Excel 8.0;";
    OleDbConnection conn = new OleDbConnection(strConn);
    OleDbDataAdapter da=new OleDbDataAdapter("SELECT * FROM [intime$]", conn);
    try
    {
    da.Fill(importData);
    }
    catch(OleDbException)
    {
    throw new Exception("Excel文件格式不正确!");

    }
    conn.Close();
    return importData;

    }

    public override int ImportData(int batchId,DataSet importData) {
    int count=0;
    using (SqlConnection conn = new SqlConnection(SysConfig.GetConnstr())) 
    {
    conn.Open();
    // using (SqlTransaction trans = conn.BeginTransaction()) 
    // {
    // try
    // {
    foreach(DataRow row in importData.Tables[0].Rows)
    {

    OverDraftDetailInfo detail=new OverDraftDetailInfo();
    detail.Batchid=batchId;
    detail.CCid=row["卡号"].ToString();
    detail.OverDraftDate=convertDate(row["起透日期"].ToString());
    detail.OverDraftQuantum=(System.Double)row["透支金额"];
    detail.Accrual=(System.Double)row["应付利息"];
    OverDraftDetailDAL.Create(detail);
    CreditCardInfo creditCardInfo=new CreditCardInfo();
    creditCardInfo.CCid=detail.CCid;
    creditCardInfo.OverDraftDate=detail.OverDraftDate;
    creditCardInfo.OverDraftQuantum=detail.OverDraftQuantum;
    creditCardInfo.Accrual=detail.Accrual;
    CreditCardDAL.UpdateOverDraft(creditCardInfo);
    count++;
    }
    // }
    // catch(Exception e)
    // {
    // trans.Rollback();
    // throw  e;
    // }
    // }
    }


    return count; }
      

  2.   

    http://dev.csdn.net/develop/article/46/46002.shtmhttp://dev.csdn.net/develop/article/45/45210.shtm给分。。
      

  3.   

    上述的从DataGrid都是用ASP.Net里面用到的,有没有直接在CS架构下面的啊?
      

  4.   

    http://support.microsoft.com/default.aspx?scid=kb;zh-cn;247412
      

  5.   

    看看这个
    http://blog.csdn.net/zr1982930/archive/2004/12/16/218057.aspx
      

  6.   

    DataLife(自由风): 帮忙贴个链接出来,谢谢。
    jasminetea : 首先很感谢你贴的这个VB和Excel的,这个我以前已经实现了,现在需要用到C#(CS)架构下DateGrid和Excel,不知道你用过没有。版主大哥,难道我要再开帖子才能让你们注意么?
      

  7.   

    完整的类!!!
    using System;
    using System.Windows.Forms;
    using System.Data;
    using System.Data.Common;namespace PJMG.Client
    {
    /// <summary>
    /// ExcelClass 的摘要说明。
    /// </summary>
    public class ExcelClass
    {
    int startRow;    //开始行
    int startCol;   //开始列
    int totalRow;   //总共行  --正式数据部分,不包括头和尾
    int totalCol;   //总共列 int HeaderInterContext; DataGrid dataGrid;
    string CaptionText;
    public ExcelClass()
    {
    //
    // TODO: 在此处添加构造函数逻辑
    //
    startRow=2;
    startCol=2;
    HeaderInterContext=1;
    } public void OutPutExcel(DataGrid dataGrid,string CaptionText)
    {
    this.dataGrid=dataGrid;
    this.CaptionText=CaptionText;
    System.Threading.Thread thread=new System.Threading.Thread(new System.Threading.ThreadStart(OutPut));
    thread.Start();
    } private void OutPut()
    {
    int contextStartRow=startRow+HeaderInterContext+1; string saveFileName="";
    bool fileSaved=false;
    SaveFileDialog saveDialog=new SaveFileDialog();
    saveDialog.DefaultExt ="xls";
    saveDialog.Filter="Excel文件|*.xls";
    saveDialog.FileName ="Sheet1";
    saveDialog.ShowDialog();
    saveFileName=saveDialog.FileName;
    if(saveFileName.IndexOf(":")<0) return; //被点了取消
    Excel.Application xlApp=new Excel.ApplicationClass(); if(xlApp==null)
    {
    MessageBox.Show("无法创建Excel对象,可能您的机子未安装Excel");
    return;
    } Excel.Workbooks workbooks=xlApp.Workbooks;
    Excel.Workbook  workbook=workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
    Excel.Worksheet  worksheet=(Excel.Worksheet)workbook.Worksheets[1];//取得sheet1
    Excel.Range range; string oldCaption=dataGrid.CaptionText; worksheet.Cells[startRow,startCol]=CaptionText;        // 写入标题
    worksheet.get_Range(xlApp.Cells[startRow,startCol],xlApp.Cells[startRow,startCol]).Font.Bold=true;  //设置标题格式
    worksheet.get_Range(xlApp.Cells[startRow,startCol],xlApp.Cells[startRow,startCol]).Font.Size=22;
    //写入字段
    totalCol=dataGrid.TableStyles[0].GridColumnStyles.Count;
    for(int i=0;i<totalCol;i++)
    {
    worksheet.Cells[contextStartRow,i+startCol]=dataGrid.TableStyles[0].GridColumnStyles[i].HeaderText;  
    range=(Excel.Range)worksheet.Cells[contextStartRow,i+startCol];
    range.Interior.ColorIndex = 19;
    range.Font.Bold = true;
    range.HorizontalAlignment=Excel.XlVAlign.xlVAlignCenter;
    } System.Data.DataSet dataSet=(DataSet)dataGrid.DataSource;
    System.Data.DataTable tableView=dataSet.Tables[dataGrid.DataMember];
    totalRow=tableView.Rows.Count;
    //写入数值
    long rowRead=0;
    float percent=0;
    Excel.Style style;
    for(int r=0;r<totalRow;r++)
    {
    for(int i=0;i<totalCol;i++)
    {
    dataGrid.Select(r);
    if(dataGrid[r,i].GetType()==System.Type.GetType("System.DateTime"))
    {
    DateTime dateTime=Convert.ToDateTime(dataGrid[r,i].ToString());
    if(dateTime.Hour==0 && dateTime.Minute==0 && dateTime.Second==0)
    worksheet.Cells[r+contextStartRow+1,i+startCol]=(Convert.ToDateTime(dataGrid[r,i].ToString())).ToString("yyyy-MM-dd");
    else
    worksheet.Cells[r+contextStartRow+1,i+startCol]=(Convert.ToDateTime(dataGrid[r,i].ToString())).ToString("yyyy-MM-dd HH:mm:ss");
    }
    else if(dataGrid[r,i].GetType()==System.Type.GetType("System.String"))
    {
    string str=(string)dataGrid[r,i];
    // range=(Excel.Range)worksheet.Cells[r+contextStartRow+1,i+startCol];
    // try
    // {
    // style=workbook.Styles["vnd.ms-excel.numberformat:@"];
    // }
    // catch
    // {
    // style=workbook.Styles.Add("vnd.ms-excel.numberformat:@",Type.Missing);
    // }
    // range.Style=style;
    worksheet.Cells[r+contextStartRow+1,i+startCol]=""+str.ToString() +"";
    }
    else
    {
    worksheet.Cells[r+contextStartRow+1,i+startCol]=dataGrid[r,i].ToString();
    }
    range=(Excel.Range)worksheet.Cells[r+contextStartRow+1,i+startCol];
    range.HorizontalAlignment=Excel.XlVAlign.xlVAlignCenter;
    }
    rowRead++;
    percent=((float)(100*rowRead)) /totalRow;    
    dataGrid.CaptionText = "正在导出数据["+ percent.ToString("0.00")  +"%]...";
    System.Windows.Forms.Application.DoEvents();
    }

    //加一个总计行
    totalRow++;
    xlApp.Cells[contextStartRow+totalRow,startCol]="总计";
    worksheet.get_Range(xlApp.Cells[contextStartRow+totalRow,startCol],xlApp.Cells[contextStartRow+totalRow,startCol]).HorizontalAlignment=Excel.XlVAlign.xlVAlignCenter;
    //设置报表表格为最适应宽度
    worksheet.get_Range(xlApp.Cells[contextStartRow,startCol],xlApp.Cells[totalRow+contextStartRow,totalCol+startCol]).Select();           
    worksheet.get_Range(xlApp.Cells[contextStartRow,startCol],xlApp.Cells[totalRow+contextStartRow,totalCol+startCol]).Columns.AutoFit();

    //设置标题跨列居中
    worksheet.get_Range(xlApp.Cells[startRow,startCol],xlApp.Cells[startRow,totalCol+startCol-1]).Select();           
    worksheet.get_Range(xlApp.Cells[startRow,startCol],xlApp.Cells[startRow,totalCol+startCol-1]).HorizontalAlignment=Excel.XlHAlign.xlHAlignCenterAcrossSelection;    
           

    //设置边框
    worksheet.get_Range(xlApp.Cells[contextStartRow,startCol],xlApp.Cells[totalRow+contextStartRow,totalCol+startCol-1]).Borders.LineStyle=1;
    worksheet.get_Range(xlApp.Cells[contextStartRow,startCol],xlApp.Cells[contextStartRow,totalCol+startCol-1]).Borders[Excel.XlBordersIndex.xlEdgeTop].Weight=Excel.XlBorderWeight.xlThick;
    worksheet.get_Range(xlApp.Cells[contextStartRow,startCol],xlApp.Cells[totalRow+contextStartRow,startCol]).Borders[Excel.XlBordersIndex.xlEdgeLeft].Weight=Excel.XlBorderWeight.xlThick;
    worksheet.get_Range(xlApp.Cells[contextStartRow,totalCol+startCol-1],xlApp.Cells[totalRow+contextStartRow,totalCol+startCol-1]).Borders[Excel.XlBordersIndex.xlEdgeRight].Weight=Excel.XlBorderWeight.xlThick;
    worksheet.get_Range(xlApp.Cells[totalRow+contextStartRow,startCol],xlApp.Cells[totalRow+contextStartRow,totalCol+startCol-1]).Borders[Excel.XlBordersIndex.xlEdgeBottom].Weight=Excel.XlBorderWeight.xlThick;
    //  设置页面
    worksheet.PageSetup.LeftHeader=PJMG.Client.SystemVariat.UnitShortName;
    worksheet.PageSetup.LeftFooter="制表人:  "+PJMG.Client.UserVariat.Manname;
    worksheet.PageSetup.CenterFooter="制表时间: "+System.DateTime.Today.ToShortDateString();
    worksheet.PageSetup.RightFooter="第&P页  共&N页"; if(saveFileName!="")
    {    
    try
    {
    workbook.Saved =true;   
    workbook.SaveCopyAs(saveFileName);
    fileSaved=true;
    }
    catch(Exception ex)
    {
    fileSaved=false;
    MessageBox.Show("导出文件时出错,文件可能正被打开!\n"+ex.Message);
    }
    }
    else
    {
    fileSaved=false;
    }   
    xlApp.Quit();
    xlApp=null;
    GC.Collect();//强行销毁
    try
    {
    if(fileSaved & System.IO.File.Exists(saveFileName)) System.Diagnostics.Process.Start("Excel.exe",saveFileName);
    }
    catch(Exception ex)
    {
    MessageBox.Show("找不到Excel.exe文件"+ex.Message);
    } // xSt.SelectedSheets.PrintPreview;   //打印浏览功能 dataGrid.CaptionText=oldCaption;
    }
    }
    }
      

  8.   

    http://blog.csdn.net/landlordh/archive/2005/01/14/253457.aspx
        'Power by:Landlordh
        '列宽默认为datagird的tablestyles(0)列宽的五分之一
        'G2E(dg1)
        Public Function G2E(ByVal dg As DataGrid)
            Dim dt As New DataTable
            Try
                dt = CType(dg.DataSource, DataTable)
            Catch ex As Exception
                MsgBox(ex.Message)
                Exit Function
            End Try
            Dim total_col As Integer = dt.Columns.Count
            Dim total_row As Integer = dt.Rows.Count
            If total_col < 1 Or total_row < 1 Then
                MsgBox("没有可供导入的数据!", MsgBoxStyle.Information, "系统提示")
                Exit Function
            End If        'killEXCEL()        '要先在引用中添加EXCEL组件
            Dim xlApp As New Excel.Application
            Dim xlBook As Excel.Workbook
            Dim xlSheet As Excel.Worksheet        Try
                GC.Collect()
                xlBook = xlApp.Workbooks().Add
                xlSheet = xlBook.Worksheets("sheet1")
                xlApp.Visible = True            Try
                    With xlSheet.PageSetup
                        .RightMargin = 1
                        .LeftMargin = 1
                        .CenterHorizontally = True
                        .CenterHeader = "&24 报表"
                        .RightFooter = "&P of &N"
                    End With
                Catch ex As Exception
                    MsgBox(ex.ToString)
                    Exit Function
                End Try            Dim Col As Integer
                Dim Row As Integer
                Dim st_row As Integer = 5 '数据列头开始行,(列头)
                Dim trueCol As Integer = 0
                For Col = 0 To total_col - 1
                    If dg.TableStyles.Item(0).GridColumnStyles.Item(Col).Width > 0 Then trueCol += 1
                Next            Dim TitleArray(4, 0) As Object
                Dim HeaderArray(0, trueCol - 1) As Object
                Dim DataArray(total_row - 1, trueCol - 1) As Object            TitleArray(0, 0) = "TO:"
                TitleArray(1, 0) = "FORM:"
                TitleArray(2, 0) = ""
                TitleArray(3, 0) = ""
                xlSheet.Range("A1").Resize(4, 1).Value = TitleArray            Dim i As Integer = 0
                For Col = 0 To total_col - 1
                    If dg.TableStyles.Item(0).GridColumnStyles.Item(Col).Width > 0 Then
                        i += 1
                        HeaderArray(0, i - 1) = dt.Columns(Col).ColumnName
                        '设列宽,默认为datagird列宽的五分之一
                        xlSheet.Cells(st_row, i).ColumnWidth = dg.TableStyles.Item(0).GridColumnStyles.Item(Col).Width / 5
                    End If
                Next
                xlSheet.Range("A" & st_row).Resize(st_row, trueCol).Value = HeaderArray            For Row = 0 To total_row - 1
                    i = 0
                    For Col = 0 To total_col - 1
                        If dg.TableStyles.Item(0).GridColumnStyles.Item(Col).Width > 0 Then
                            i += 1
                            DataArray(Row, i - 1) = dt.Rows(Row).Item(Col)
                        End If
                    Next
                Next
                xlSheet.Range("A" & st_row + 1).Resize(total_row, trueCol).Value = DataArray            With xlSheet
                    .Range(.Cells(st_row, 1), .Cells(st_row, trueCol)).Font.Bold = True
                    .Range(.Cells(st_row, 1), .Cells(st_row, trueCol)).HorizontalAlignment = 3
                    .Range(.Cells(st_row, 1), .Cells(total_row + st_row, trueCol)).Borders.LineStyle = 1
                    '设置数据区第一列到第二列为居中
                    .Range(.Cells(st_row, 1), .Cells(total_row + st_row, 2)).HorizontalAlignment = 3
                End With            xlApp.ActiveWorkbook.PrintPreview()
            Catch ex As Exception
                xlSheet = Nothing
                xlApp.DisplayAlerts = False
                xlBook.RunAutoMacros(Excel.XlRunAutoMacro.xlAutoClose)
                xlBook.Close()
                xlBook = Nothing
                xlApp.Quit()
                xlApp.DisplayAlerts = True
                xlApp = Nothing
                GC.Collect()
                MsgBox(ex.ToString)
                Exit Function
            End Try
            xlSheet = Nothing
            xlApp.DisplayAlerts = False
            xlBook.RunAutoMacros(Excel.XlRunAutoMacro.xlAutoClose)
            xlBook.Close()
            xlBook = Nothing
            xlApp.Quit()
            xlApp.DisplayAlerts = True
            xlApp = Nothing
            GC.Collect()
        End Function
      

  9.   

    Private Sub Out_Excel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Out_Excel.Click
            Dim objExcel As New OWC.Spreadsheet
            Dim myRow As DataRow
            Dim myColumn As New DataColumn
            Dim RowCount As Object
            Dim ColumnCount As Object
            Dim FileName As String = "seweding_analyse.xls"
            Dim FileAndPath As String = "C:\" & FileName        Dim xlsheet As New SpreadsheetClass
            Dim i As Integer = 0
            Dim j As Integer = 0        Dim oItem As DataGridColumn
            For Each oItem In dgd_result.Columns
                xlsheet.ActiveSheet.Cells(1, i + 1) = oItem.HeaderText            xlsheet.Range(xlsheet.Cells(1, 1), xlsheet.Cells(1, i + 1)).Font.Bold = True
                xlsheet.Range(xlsheet.Cells(1, 1), xlsheet.Cells(1, i + 1)).Font.Color = "red"
                i = i + 1
            Next        Dim numbercols As Integer = dgd_result.Items.Item(0).Cells.Count
            For j = 0 To dgd_result.Items.Count - 1
                For i = 0 To numbercols - 1
                    xlsheet.Range(xlsheet.Cells(2, 2), xlsheet.Cells(j + 2, i + 1)).Font.Color = "blue"
                    'xlsheet.Range(xlsheet.Cells(100, 100), xlsheet.Cells(j + 2, i + 1)).Font.Color = "blue"
                    xlsheet.Range(xlsheet.Cells(90, 90), xlsheet.Cells(j + 2, i + 1)).Cells.ColumnWidth = 90
                    'xlsheet.Range(xlsheet.Cells(100, 100), xlsheet.Cells(j + 2, i + 1)).Columns.ColumnWidth = 100
                    'xlsheet.Range(xlsheet.Cells(2, 1), xlsheet.Cells(j + 2, i + 1)).AutoFitColumns()
                    'xlsheet.Range(xlsheet.Cells(100, 100), xlsheet.Cells(j + 2, i + 1)).AutoFitColumns()                xlsheet.ActiveSheet.Cells(j + 2, i + 1) = dgd_result.Items.Item(j).Cells(i).Text.Replace("&nbsp;", " ")
                Next
            Next
            xlsheet.ActiveSheet.Columns.InsertColumns(0)
            xlsheet.ActiveSheet.Rows.InsertRows(0)
            xlsheet.ActiveSheet.Cells(1, 1) = "列名1"
            xlsheet.ActiveSheet.Cells(1, 2) = "列名2"
            xlsheet.ActiveSheet.Cells(1, 3) = "列名3"
            xlsheet.ActiveSheet.Cells(1, 4) = "列名4"
            xlsheet.ActiveSheet.Cells(1, 5) = "列名5"
            xlsheet.ActiveSheet.Cells(1, 6) = "列名6"
            xlsheet.ActiveSheet.Cells(1, 7) = "列名7"
            xlsheet.ActiveSheet.Cells(1, 8) = "列名8"
              
            xlsheet.ActiveSheet.Rows(1).Font.Bold = True        Try            xlsheet.ActiveSheet.Export(FileAndPath, OWC.SheetExportActionEnum.ssExportActionNone)
                '  xlsheet.ActiveSheet.Export(Server.MapPath(".") + "\Images\" + Me.xlfile.Text, OWC.SheetExportActionEnum.ssExportActionNone)
                '  xlsheet.ActiveSheet.Export(Server.MapPath("xlsdata") + "\\" + Me.xlfile.Text, OWC.SheetExportActionEnum.ssExportActionNone)
            Catch ex As System.Runtime.InteropServices.COMException            Response.Write("xx:" + ex.Message)
            End Try        Response.ContentType = "application/octet-stream"
            Response.AddHeader("Content-Disposition", "attachment; filename=" & FileName)
            Response.Flush()        Response.WriteFile(FileAndPath)
        End Sub
      

  10.   

    http://www.syncfusion.com/FAQ/WinForms/FAQ_c44c.asp