需要在同一个excel表中写两个结果

时间:2016-05-29 14:16:28

标签: c# asp.net .net excel

 xlApp = new Excel.Application();
        xlWorkBook = xlApp.Workbooks.Add(misValue);
        xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

        OleDbDataAdapter dscmd = new OleDbDataAdapter("select distinct Ticket_no from Tickets where date_dt='" + dateTimePicker1.Value.ToShortDateString() + "' and Type='Closure'  and queueName='" + comboBox1.Text + "'", cont1);
        DataSet ds = new DataSet();
        dscmd.Fill(ds);
        OleDbDataAdapter dtcmd = new OleDbDataAdapter("select distinct Ticket_no from Tickets where date_dt='" + dateTimePicker1.Value.ToShortDateString() + "' and Type='Reassigned'  and queueName='" + comboBox1.Text + "'", cont1);
        DataSet dt = new DataSet();
        dtcmd.Fill(dt);
        xlWorkSheet.Cells[1, 1] = "Closure";
        xlWorkSheet.Cells[1, 2] = "Reassigned";

        for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
        {
            for (j = 0; j <= ds.Tables[0].Columns.Count - 1; j++)
            {

                data = ds.Tables[0].Rows[i].ItemArray[j].ToString();
                xlWorkSheet.Cells[i + 2, j + 1] = data;

            }
        }

        xlWorkBook.SaveAs("Ticket_Closer_"+dateTimePicker1.Value.ToShortDateString()+".xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
        xlWorkBook.Close(true, misValue, misValue);
        xlApp.Quit();

        releaseObject(xlWorkSheet);
        releaseObject(xlWorkBook);
        releaseObject(xlApp);

我需要在第一列中编写第一个选择查询结果,在同一个Excel工作表的第二列中编写第二个选择查询结果。请帮我正确编码。

1 个答案:

答案 0 :(得分:0)

请原谅我的英文翻译google translate make。 我用VB.NET编写了这个,你可以在C#类中快速重写。

这是将vb.net转换为C#的众多在线工具之一 http://www.developerfusion.com/tools/convert/vb-to-csharp/

如果您愿意,可以使用没有信息的Excel文件,读取内存中的空文件,然后将DataTable类型变量的结果直接写入对象,然后保存。这是我的首选方法,在内存中操作DataTable要快得多 这是如何实现它的一个例子

Dim ColDef As xlsRW.fldType
ColDef = New xlsRW.fldType
ColDef.fldName = "FieldName"
ColDef.fldSize = 200
ColDef.fldType = xlsRW.FieldsType.char
xlsWriter.ColumnAdd(colDef)
ColDef = New xlsRW.fldType
ColDef.fldName = "DateField"
ColDeffldType = xlsRW.FieldsType.date
xlsWriter.ColumnAdd(colDef)
xlsWriter.CreateWorkbook("WB")

Esta es la clase

Imports System.Data.OleDb
Imports System.Collections
Public Class xlsRW
  Public Enum FieldsType As Byte
    [char]
    [date]
    [float]
    [currency]
  End Enum
  Public Structure fldType
    Public fldName As String
    Public fldSize As UShort
    Public fldType As FieldsType
    Public fldValue As Object
  End Structure
  Private blnHasHeader As Boolean = True
  Private strSheetName As String = String.Empty
  Private strFileName As String = String.Empty

  Private blnXLSOpen As Boolean = False
  Private oleConn As OleDbConnection
  Private oleCmd As OleDbCommand
  Private oleDA As OleDbDataAdapter
  Private htFields As New Hashtable
#Region " Properties "
  Public Property FileName() As String
    Get
      Return strFileName
    End Get
    Set(ByVal value As String)
      strFileName = value
    End Set
  End Property
  Public Property SheetName() As String
    Get
      Return strSheetName
    End Get
    Set(ByVal value As String)
      strSheetName = value
    End Set
  End Property
  Public Property HasHeader() As Boolean
    Get
      Return blnHasHeader
    End Get
    Set(ByVal value As Boolean)
      blnHasHeader = value
    End Set
  End Property
  Public ReadOnly Property IsXLSOpen As Boolean
    Get
      Return blnXLSOpen
    End Get
  End Property
#End Region
  Public Sub Open()
    If strFileName.Length = 0 Then
      Throw New Exception("Filename was not assigned.")
    End If
    Me.Open(strFileName)
  End Sub
  Public Sub Open(ByVal strFileName As String)
    Try

      Dim strConn As String = String.Empty
      If IO.Path.GetExtension(strFileName).ToLower = ".xls" Then
        strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFileName & ";" & "Extended Properties=""Excel 8.0;HDR=YES;IMEX=1;READONLY=FALSE;"""
      ElseIf IO.Path.GetExtension(strFileName).ToLower = ".xlsx" Then
        strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strFileName & ";" & "Extended Properties=""Excel 12.0 Xml;HDR=YES;IMEX=1;READONLY=FALSE;"""
      End If
      If Not blnHasHeader Then
        strConn = strConn.Replace("YES", "NO")
      End If
      oleConn = New OleDbConnection
      oleConn.ConnectionString = strConn

      oleConn.Open()
      blnXLSOpen = True
    Catch ex As Exception
      Throw ex
    End Try
  End Sub
  Public Sub ColumnAdd(colDef As fldType)
    If htFields.ContainsKey(colDef.fldName) Then
      Throw New Exception("Field already exist")
    End If
    Dim strField As String = String.Empty
    strField = colDef.fldName & " " & colDef.fldType.ToString
    If colDef.fldType = FieldsType.char Then
      strField += " (" & colDef.fldSize & ")"
    End If
    htFields.Add(colDef.fldName, strField)
  End Sub
  Public Sub ColumnRemove(colDefName As String)
    If Not htFields.ContainsKey(colDefName) Then
      Throw New Exception("Field doesn't exist")
    End If
    htFields.Remove(colDefName)
  End Sub
  Public Sub ColumnUpdate(colDef As fldType)
    If Not htFields.ContainsKey(colDef.fldName) Then
      Throw New Exception("Field doesn't exist")
    End If
    Dim strField As String = String.Empty
    strField = colDef.fldName & " " & colDef.fldType.ToString
    If colDef.fldType = FieldsType.char Then
      strField += " (" & colDef.fldSize & ")"
    End If
    htFields.Item(colDef.fldName) = strField
  End Sub
  Public Sub ColumnClear()
    htFields.Clear()
  End Sub
  Public Sub CreateWorkbook(ByVal strSheetName As String)
    If Not blnXLSOpen Then
      Throw New Exception("Connection is unassigned or closed.")
    End If
    If htFields.Count = 0 Then
      Throw New Exception("No fields defined.")
    End If
    Try
      oleCmd = New OleDbCommand
      oleCmd.Connection = oleConn
      Dim strCmdText As String = "CREATE TABLE " & strSheetName & " ("
      For Each strFldDesign As String In htFields.Keys
        strCmdText += htFields(strFldDesign) & ", "
      Next
      oleCmd.CommandText += strCmdText.Substring(0, strCmdText.Length - 2) & ")"

      oleCmd.ExecuteNonQuery()

    Catch ex As Exception

    End Try
  End Sub
  Public Sub Close()
    oleConn.Close()
    blnXLSOpen = False
  End Sub
#Region " Select "
  Public Function SelectWorksheet() As DataTable
    If Not blnXLSOpen Then
      Throw New Exception("Connection is unassigned or closed.")
    End If
    If strSheetName.Length = 0 Then
      Throw New Exception("Sheetname was not assigned.")
    End If
    Try
      oleDA = New OleDbDataAdapter("select * from [" & strSheetName & "$]", oleConn)
      Dim dsXLS As DataSet = New DataSet(IO.Path.GetFileNameWithoutExtension(strFileName))
      oleDA.Fill(dsXLS)
      dsXLS.Tables(0).TableName = strSheetName
      Return dsXLS.Tables(0)
    Catch ex As Exception
      Throw ex
      Return Nothing
    End Try
  End Function
  Public Function SelectWorksheet(ByVal strCell As String) As Object
    If Not blnXLSOpen Then
      Throw New Exception("Connection is unassigned or closed.")
    End If
    If strSheetName.Length = 0 Then
      Throw New Exception("Sheetname was not assigned.")
    End If
    Dim strCellRange As String = strCell & ":" & strCell
    Try
      oleCmd = New OleDbCommand("SELECT * FROM [" & strSheetName & "$" & strCellRange & "]", oleConn)
      Return oleCmd.ExecuteScalar()
    Catch ex As Exception
      Throw ex
      Return Nothing
    End Try
  End Function
#End Region
#Region " Insert "
  Public Sub InsertWorksheet(ByVal aryValues As ArrayList)
    If Not blnXLSOpen Then
      Throw New Exception("Connection is unassigned or closed.")
    End If
    If strSheetName.Length = 0 Then
      Throw New Exception("Sheetname was not assigned.")
    End If
    Try
      Dim oleDA As New OleDbDataAdapter()
      oleCmd = New OleDbCommand("Select * From [" & strSheetName & "$]", oleConn)
      oleDA.SelectCommand = oleCmd
      Dim dsXLS As DataSet = New DataSet(IO.Path.GetFileNameWithoutExtension(strFileName))
      oleDA.Fill(dsXLS, strSheetName)
      Dim strInsertCmd As String = String.Empty
      Dim strColumn As String = String.Empty
      strInsertCmd = "INSERT INTO [" & strSheetName & "$] ("
      For bteCnt As Byte = 0 To dsXLS.Tables(strSheetName).Columns.Count - 1
        strInsertCmd += "[" & dsXLS.Tables(strSheetName).Columns.Item(bteCnt).ColumnName & "], "
      Next
      strInsertCmd = strInsertCmd.Substring(0, strInsertCmd.Length - 2)
      strInsertCmd += ") VALUES ("
      For bteCnt As Byte = 0 To dsXLS.Tables(strSheetName).Columns.Count - 1
        strInsertCmd += "?, "
      Next
      strInsertCmd = strInsertCmd.Substring(0, strInsertCmd.Length - 2) & ")"
      oleDA.InsertCommand = New OleDbCommand(strInsertCmd, oleConn)
      For bteCnt As Byte = 0 To dsXLS.Tables(strSheetName).Columns.Count - 1
        strColumn = dsXLS.Tables(strSheetName).Columns.Item(bteCnt).ColumnName
        Select Case aryValues.Item(bteCnt).GetType.Name
          Case "String"
            oleDA.InsertCommand.Parameters.Add("@" & strColumn, OleDbType.VarChar)
          Case "DateTime"
            oleDA.InsertCommand.Parameters.Add("@" & strColumn, OleDbType.Date)
          Case "Decimal", "Int32"
            oleDA.InsertCommand.Parameters.Add("@" & strColumn, OleDbType.Numeric)
          Case "DBNull"
            oleDA.InsertCommand.Parameters.Add("@" & strColumn, OleDbType.Empty)
        End Select
        oleDA.InsertCommand.Parameters.Item("@" & strColumn).Value = aryValues.Item(bteCnt)
      Next
      oleDA.InsertCommand.ExecuteNonQuery()
      oleDA.Update(dsXLS, strSheetName)
    Catch ex As Exception
      Throw ex
    End Try
  End Sub
  Public Sub InsertWorksheet(ByVal drRow As DataRow)
    If Not blnXLSOpen Then
      Throw New Exception("Connection is unassigned or closed.")
    End If
    If strSheetName.Length = 0 Then
      Throw New Exception("Sheetname was not assigned.")
    End If
    Try
      Dim oleDA As New OleDbDataAdapter()
      oleCmd = New OleDbCommand("Select * From [" & strSheetName & "$]", oleConn)
      oleDA.SelectCommand = oleCmd
      Dim dsXLS As DataSet = New DataSet(IO.Path.GetFileNameWithoutExtension(strFileName))
      oleDA.Fill(dsXLS, strSheetName)
      Dim strInsertCmd As String = String.Empty
      Dim strColumn As String = String.Empty
      strInsertCmd = "INSERT INTO [" & strSheetName & "$] ("
      For bteCnt As Byte = 0 To dsXLS.Tables(strSheetName).Columns.Count - 1
        strInsertCmd += "[" & dsXLS.Tables(strSheetName).Columns.Item(bteCnt).ColumnName & "], "
      Next
      strInsertCmd = strInsertCmd.Substring(0, strInsertCmd.Length - 2)
      strInsertCmd += ") VALUES ("
      For bteCnt As Byte = 0 To dsXLS.Tables(strSheetName).Columns.Count - 1
        strInsertCmd += "?, "
      Next
      strInsertCmd = strInsertCmd.Substring(0, strInsertCmd.Length - 2) & ")"
      oleDA.InsertCommand = New OleDbCommand(strInsertCmd, oleConn)
      For bteCnt As Byte = 0 To dsXLS.Tables(strSheetName).Columns.Count - 1
        strColumn = dsXLS.Tables(strSheetName).Columns.Item(bteCnt).ColumnName
        Select Case drRow.Item(bteCnt).GetType.Name
          Case "String"
            oleDA.InsertCommand.Parameters.Add("@" & strColumn, OleDbType.VarChar)
          Case "DateTime"
            oleDA.InsertCommand.Parameters.Add("@" & strColumn, OleDbType.Date)
          Case "Decimal"
            oleDA.InsertCommand.Parameters.Add("@" & strColumn, OleDbType.Numeric)
        End Select
        oleDA.InsertCommand.Parameters.Item("@" & strColumn).Value = drRow.Item(bteCnt)
      Next
      oleDA.InsertCommand.ExecuteNonQuery()
      oleDA.Update(dsXLS, strSheetName)
    Catch ex As Exception
      Throw ex
    End Try
  End Sub
  Public Sub InsertWorksheet(ByVal dtData As DataTable)
    If Not blnXLSOpen Then
      Throw New Exception("Connection is unassigned or closed.")
    End If
    If strSheetName.Length = 0 Then
      Throw New Exception("Sheetname was not assigned.")
    End If
    Try
      Dim oleDA As New OleDbDataAdapter()
      oleCmd = New OleDbCommand("Select * From [" & strSheetName & "$]", oleConn)
      oleDA.SelectCommand = oleCmd
      Dim dsXLS As DataSet = New DataSet(IO.Path.GetFileNameWithoutExtension(strFileName))
      oleDA.Fill(dsXLS, strSheetName)
      Dim strInsertCmd As String = String.Empty
      Dim strColumn As String = String.Empty
      For Each dtRow As DataRow In dtData.Rows
        strInsertCmd = "INSERT INTO [" & strSheetName & "$] ("
        For bteCnt As Byte = 0 To dsXLS.Tables(strSheetName).Columns.Count - 1
          strInsertCmd += "[" & dsXLS.Tables(strSheetName).Columns.Item(bteCnt).ColumnName & "], "
        Next
        strInsertCmd = strInsertCmd.Substring(0, strInsertCmd.Length - 2)
        strInsertCmd += ") VALUES ("
        For bteCnt As Byte = 0 To dsXLS.Tables(strSheetName).Columns.Count - 1
          strInsertCmd += "?, "
        Next
        strInsertCmd = strInsertCmd.Substring(0, strInsertCmd.Length - 2) & ")"
        oleDA.InsertCommand = New OleDbCommand(strInsertCmd, oleConn)
        For bteCnt As Byte = 0 To dsXLS.Tables(strSheetName).Columns.Count - 1
          strColumn = dsXLS.Tables(strSheetName).Columns.Item(bteCnt).ColumnName
          Select Case dtData.Columns(bteCnt).DataType.Name
            Case "String"
              oleDA.InsertCommand.Parameters.Add("@" & strColumn, OleDbType.VarChar)
            Case "DateTime"
              oleDA.InsertCommand.Parameters.Add("@" & strColumn, OleDbType.Date)
            Case "Decimal"
              oleDA.InsertCommand.Parameters.Add("@" & strColumn, OleDbType.Numeric)
          End Select
          oleDA.InsertCommand.Parameters.Item("@" & strColumn).Value = dtRow.Item(bteCnt)
          'oleDA.InsertCommand.Parameters.Item("@" & strColumn).SourceColumn = strColumn
        Next
        oleDA.InsertCommand.ExecuteNonQuery()
      Next
      oleDA.Update(dsXLS, strSheetName)
    Catch ex As Exception
      Throw ex
    End Try
  End Sub
#End Region
#Region " Update "
  Public Sub UpdateWorksheet(ByVal aryFields() As String, aryValues() As Object, strWhere As String)
    If Not blnXLSOpen Then
      Throw New Exception("Connection is unassigned or closed.")
    End If
    If strSheetName.Length = 0 Then
      Throw New Exception("Sheetname was not assigned.")
    End If
    Try


    Catch ex As Exception
      Throw ex
    End Try
  End Sub
  Public Sub UpdateWorksheet(ByVal strCell As String, objValue As Object)
    If Not blnXLSOpen Then
      Throw New Exception("Connection is unassigned or closed.")
    End If
    If strSheetName.Length = 0 Then
      Throw New Exception("Sheetname was not assigned.")
    End If
    Try
      oleCmd = New OleDbCommand(String.Empty, oleConn)
      oleCmd.CommandText = "UPDATE [" & strSheetName & "$" & strCell & ":" & strCell & "] SET F1 = ?"
      Dim oleType As OleDbType
      Select Case objValue.GetType.Name
        Case "String"
          oleType = OleDbType.VarChar
        Case "DateTime"
          oleType = OleDbType.Date
        Case "Decimal"
          oleType = OleDbType.Numeric
      End Select
      oleCmd.Parameters.Add("@F1", oleType, 0, "F1")
      oleCmd.Parameters(0).Value = objValue
      oleCmd.ExecuteNonQuery()
    Catch ex As Exception
      Throw ex
    End Try
  End Sub
#End Region
End Class