Пример работы с экселем. Файл немного обрабатывается и преобразуется к тексту с разделителями. Вырван из контекста и работать не будет сам по себе. В программе анализируются поля и приводятся к нужному виду. Попутно показаны разные другие вещи.
Код
Private Sub Button2_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim key As Integer
Dim rez As Windows.Forms.DialogResult
Dim firstDate As Date
Dim tFile As String
Dim dR1 As String
Dim dR2 As String
dR1 = ""
dR2 = ""
tFile = ""
tFile = Path.GetTempFileName()
Dim myFileInfo As New FileInfo(tFile)
myFileInfo.Attributes = FileAttributes.Temporary
Try
OpenFileDialog1.CheckFileExists = True
OpenFileDialog1.CheckPathExists = True
OpenFileDialog1.DefaultExt = "xls"
OpenFileDialog1.DereferenceLinks = True
OpenFileDialog1.Filter = "MS_Excel files (*.xls)|*.xls|All files|*.*"
OpenFileDialog1.Multiselect = False
OpenFileDialog1.RestoreDirectory = True
OpenFileDialog1.ShowReadOnly = False
OpenFileDialog1.ReadOnlyChecked = False
OpenFileDialog1.Title = "Excel. Открыть..."
rez = OpenFileDialog1.ShowDialog
If rez = Windows.Forms.DialogResult.OK Then
firstDate = Now
ToolStripStatusLabel1.Text = "Выполняется загрузка. Ждите..."
ToolStripStatusLabel1.Visible = True
ToolStripProgressBar1.Visible = True
Dim oExcel As New Microsoft.Office.Interop.Excel.Application
Dim oBook As Microsoft.Office.Interop.Excel.Workbook
Dim oSheet As Microsoft.Office.Interop.Excel.Worksheet
oExcel = New Microsoft.Office.Interop.Excel.Application
oBook = oExcel.Workbooks.Open(OpenFileDialog1.FileName)
oExcel.DisplayAlerts = False
oSheet = oBook.Sheets(1)
oSheet.Rows("1:6").delete()
System.Runtime.InteropServices.Marshal.ReleaseComObject(oSheet)
oSheet = Nothing
oBook.SaveAs(tFile, Microsoft.Office.Interop.Excel.XlFileFormat.xlTextWindows)
System.Runtime.InteropServices.Marshal.ReleaseComObject(oBook)
oBook = Nothing
oExcel.Quit()
System.Runtime.InteropServices.Marshal.ReleaseComObject(oExcel)
oExcel = Nothing
GC.Collect()
End If
Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser( _
tFile, Encoding.GetEncoding(1251), True)
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.Delimiters = New String() {vbTab}
Dim currentRow As String()
While Not MyReader.EndOfData
key += 1
Dim inst As New CivilSps()
Try
currentRow = MyReader.ReadFields()
inst.nPP = CStr(key + 6)
inst.Adres = Trim(Trim(UCase(currentRow.GetValue(9))) & " д. " & _
Trim(UCase(currentRow.GetValue(10))) & " к. " & _
Trim(UCase(currentRow.GetValue(12))))
dR1 = Trim(currentRow.GetValue(4))
If Len(dR1) < 2 Then
dR1 = "0" & dR1
End If
dR2 = Trim(currentRow.GetValue(5))
If Len(dR2) < 2 Then
dR2 = "0" & dR2
End If
inst.DatR = Trim(dR1 & "." & _
dR2 & "." & _
Trim(currentRow.GetValue(6)))
inst.FIO = Trim(UCase(currentRow.GetValue(1))) & " " & _
Trim(UCase(currentRow.GetValue(2))) & " " & _
Trim(UCase(currentRow.GetValue(3)))
names.Add(inst, CStr(key))
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Строка " & ex.Message & _
" имеет неверный формат. Пропущено.")
End Try
My.Application.DoEvents()
End While
End Using
ToolStripStatusLabel1.Text = "Загрузка буспешно завершена."
ToolStripProgressBar1.Visible = False
Button2.Enabled = False
If names.Count > 0 Then
Label2.Text = "Количество строк: " & names.Count
Label4.Text = "Время загрузки: " & DateDiff(DateInterval.Second, firstDate, Now) & " сек."
End If
Try
File.Delete(tFile)
tFile = ""
Catch exc As Exception
' пропуск ошибки
End Try
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Exclamation, Me.Text)
End Try
End Sub
Добавлять комментарии могут только зарегистрированные пользователи сайта.
Если у Вас уже есть учетная запись на Kbyte.Ru, пройдите процедуру авторизации.
Если Вы еще не зарегистрированы на Kbyte.Ru - зарегистрируйтесь.