Delete Blank Row in excel worksheet - asp.net

I Tried to delete blank rows from excel using the code
Dim wb As New Workbook("d:\test\book1.xls")
Dim sheets As WorksheetCollection = wb.Worksheets
Dim sheet As Worksheet = sheets(0)
sheet.Cells.DeleteBlankRows()
wb.Save("d:\test\mybook.xls")
But i am getting syntax error.Any one know the Namespace requiered to do this?

Try
ApplicationClass excel = new ApplicationClass();
Microsoft.Office.Interop.Excel.Range cellToBeDeleted = (Range)excel.Cells[rowIndex, columnIndex];
cellToBeDeleted.Delete();
Include the following namespace
using Excel = Microsoft.Office.Interop.Excel;

Try This
-Add Reference (from COM section ) Micsrosoft Excel Object Library to your project
Imports Microsoft.Office.Interop.Excel
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
delBlankRows("d:\test\book1.xls", 1)
End Sub
Private Sub delBlankRows(ByVal excelFileName As String, sheetIndex As Integer)
Dim excel As Microsoft.Office.Interop.Excel.Application = New Microsoft.Office.Interop.Excel.Application
Dim fileName = excelFileName
Dim w As Workbook = excel.Workbooks.Open(fileName)
Dim r As Range = w.Worksheets(sheetIndex).UsedRange.EntireRow.SpecialCells(XlCellType.xlCellTypeBlanks)
r.Delete()
w.Save()
w.Close()
End Sub
End Class

Related

Edit existing excel files ASP.Net without losing formatting

I have a situation where I need to use an Excel Template and insert values, then allow the user to download the updated file. I have done this using ClosedXML but as it uses a non native format for xlsx, I get a format error when opening the downloaded document and the saved instance of the document looses all formatting from the template.
I need a solution that outputs a xlsx document that is a copy of the original template, formatting and all, with the additional inserted values. If necessary, I can make a temporary copy of the template on the server.
Is there a tool I can use for this purpose?
I ended up using OpenXML. I am using VB.Net for this project and as I found very little example code in VB (mostly java or c#), I will attach it so it can be used as a reference.
The really nice thing about it is the document you get out of it does not have any validation errors or anything and all sheet formatting (text justification, font face, etc) survives.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
Dim path = Server.MapPath("~/ExcelTemplates/rfi.xlsx")
Dim templateBytes As Byte() = System.IO.File.ReadAllBytes(path)
Using templateStream As MemoryStream = New MemoryStream
templateStream.Write(templateBytes, 0, templateBytes.Length)
Using sheetInstance As SpreadsheetDocument = SpreadsheetDocument.Open(templateStream, True)
Dim worksheetPart As WorksheetPart = GetWorksheetPartByName(sheetInstance, "Sheet1")
If worksheetPart IsNot Nothing Then
'this writes "Test!!!" to cell C7
'Dim cell As Cell = GetCell(worksheetPart.Worksheet, "C", 7)
'cell.CellValue = New CellValue("Test!!!")
'another way of doing it
GetCell(worksheetPart.Worksheet, "C", 7).CellValue = New CellValue("Test12")
'this next line would change the cell's contents data type
'cell.DataType = New EnumValue(Of CellValues)(CellValues.String)
worksheetPart.Worksheet.Save()
templateStream.Position = 0
Using ms As MemoryStream = New MemoryStream
templateStream.CopyTo(ms)
Response.Buffer = True
Response.Clear()
Response.ContentType = "application/vnd.ms-excel"
Response.AppendHeader("Content-Disposition", "filename=RFI.xlsx")
ms.WriteTo(Response.OutputStream)
Response.End()
End Using
End If
End Using
End Using
End Sub
Private Shared Function GetWorksheetPartByName(ByVal document As SpreadsheetDocument, ByVal sheetName As String) As WorksheetPart
Dim sheets As IEnumerable(Of Sheet) = document.WorkbookPart.Workbook.GetFirstChild(Of Sheets)().Elements(Of Sheet)().Where(Function(s) s.Name = sheetName)
If sheets.Count() = 0 Then
Return Nothing
End If
Dim relationshipId As String = sheets.First().Id.Value
Dim worksheetPart As WorksheetPart = CType(document.WorkbookPart.GetPartById(relationshipId), WorksheetPart)
Return worksheetPart
End Function
Private Shared Function GetCell(ByVal worksheet As Worksheet, ByVal columnName As String, ByVal rowIndex As UInteger) As Cell
Dim row As Row = GetRow(worksheet, rowIndex)
If row Is Nothing Then Return Nothing
Return row.Elements(Of Cell)().Where(Function(c) String.Compare(c.CellReference.Value, columnName & rowIndex, True) = 0).First()
End Function
Private Shared Function GetRow(ByVal worksheet As Worksheet, ByVal rowIndex As UInteger) As Row
Return worksheet.GetFirstChild(Of SheetData)().Elements(Of Row)().Where(Function(r) CType(r.RowIndex, UInteger) = rowIndex).First()
End Function

Read Excel Sheet Data into DataTable or Dataset

I tried to import from Excel to a dataset and an error message occurred.
I'm studying this site http://vb.net-informations.com/excel-2007/vb.net_excel_oledb.htm
Imports System.Data
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim MyConnection As System.Data.OleDb.OleDbConnection
Dim DtSet As DataSet
Dim MyCommand As System.Data.OleDb.OleDbDataAdapter
Dim Loc As String = Application.StartupPath() + "\Param\exceldata.xlsx"
Dim strCOleCon As String = "provider=Microsoft.Jet.OLEDB.4.0; Data Source='" + Loc.Trim + "';Extended Properties=Excel 8.0;"
MyConnection = New OleDb.OleDbConnection(strCOleCon)
MyCommand = New OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection)
MyCommand.TableMappings.Add("Table", "TestTable")
DtSet = New DataSet
MyCommand.Fill(DtSet)
DataGridView1.DataSource = DtSet.Tables(0)
MyConnection.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class
U can use third party EPPLUS which is freeware.Which can import excel file into data set and it also has many functionallities to manipulate the excel file
First off I believe your connection is incorrect, you have an xlsx file but the connection is set for xls.
BTW Not sure if this is a forms or asp project but sure looks like a forms project for windows thinking about your first tag indicating asp.net.
Excel can be tricky in regards to how the connection string is setup, do you want to just read, does the first row in the sheet have column names or data, is there mixed data in a column etc.
Here is a snippet I have used to make things easier with connection but be forewarned it's not fool-proof in that you need to set HDR and IMEX correctly in the connection,
Imports System.Data.OleDb
Module ExcelOleDbConnections
''' <summary>
''' Creates a connection string on read data from an excel file
''' </summary>
''' <param name="FileName"></param>
''' <param name="Header">Yes if first row is column-names, No if first row is data</param>
''' <param name="IMEX"></param>
''' <returns></returns>
''' <remarks>
''' See following page for clarification on extended properties
''' including IMEX. Ignore C# code.
''' http://www.codeproject.com/Articles/37055/Working-with-MS-Excel-xls-xlsx-Using-MDAC-and-Oled
''' </remarks>
<System.Diagnostics.DebuggerStepThrough()> _
Public Function ExcelConnectionString(
ByVal FileName As String,
Optional ByVal Header As String = "No",
Optional ByVal IMEX As Integer = 1) As String
Dim Builder As New OleDbConnectionStringBuilder
If IO.Path.GetExtension(FileName).ToUpper = ".XLS" Then
Builder.Provider = "Microsoft.Jet.OLEDB.4.0"
Builder.Add("Extended Properties", String.Format("Excel 8.0;IMEX={0};HDR={1};", IMEX, Header))
Else
Builder.Provider = "Microsoft.ACE.OLEDB.12.0"
Builder.Add("Extended Properties", String.Format("Excel 12.0;IMEX={0};HDR={1};", IMEX, Header))
End If
Builder.DataSource = FileName
Return Builder.ToString
End Function
End Module
Sample reading a sheet where the first row is data. Note I am using optional parameters so the last two use default values
Dim dt As New DataTable
' sheet has data in first row
Using cn As New OleDb.OleDbConnection With {.ConnectionString = ExcelConnectionString(Loc)}
Using cmd As New OleDb.OleDbCommand With {.Connection = cn, .CommandText = "select * from [Sheet1$]"}
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
End Using
This example we assume the first row are field/column names
Dim dt As New DataTable
' sheet has column names for first row
Using cn As New OleDb.OleDbConnection With {.ConnectionString = ExcelConnectionString(Loc, "Yes", 0)}
Using cmd As New OleDb.OleDbCommand With {.Connection = cn, .CommandText = "select * from [Sheet1$]"}
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
End Using
Populate the DataGridView
If dt.Rows.Count > 0 Then
DataGridView1.DataSource = dt
Else
'
' recover e.g. tell user there are no records in this sheet
'
End If
Example all together
Try
Dim Loc As String = IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Param\exceldata.xlsx")
If IO.File.Exists(Loc) Then
Dim dt As New DataTable
' sheet has column names for first row
Using cn As New OleDb.OleDbConnection With {.ConnectionString = ExcelConnectionString(Loc, "Yes", 0)}
Using cmd As New OleDb.OleDbCommand With {.Connection = cn, .CommandText = "select * from [Sheet1$]"}
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
End Using
If dt.Rows.Count > 0 Then
DataGridView1.DataSource = dt
Else
'
' recover e.g. tell user there are no records in this sheet
'
End If
End If
Catch ex As Exception
MessageBox.Show("TODO")
End Try
See my windows forms examples (yes I see asp.net in your tags)
Excel and OleDb basics to advance operations

How to transfer CSV file data from a URL address to a gridview in asp.net?

I am new to ASP.net web programming and I am trying to develop a web application that will transfer CSV file data to gridview in asp.net. For example I have below url:
http://sam.sample.com/samp/DATA.CSV
Above url must be transferred in gridview using asp whenever the file has been uploaded,so meaning the date and time of uploading must be displayed also.
I have tried below codes but got an error:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
Dim cls As Class1 = New Class1()
Dim webrequest As System.Net.HttpWebRequest
Dim URL As String = "http://sam.sample.com/samp/DATA.CSV"
Dim csvuri As New Uri(URL)
webrequest = DirectCast(System.Net.HttpWebRequest.Create(csvuri), System.Net.HttpWebRequest)
webrequest.UseDefaultCredentials = True
webrequest.PreAuthenticate = True
webrequest.Credentials = New Net.NetworkCredential("ABC", "A123")
If (webrequest.GetResponse().ContentLength > 0) Then
Dim strReader As New System.IO.StreamReader(webrequest.GetResponse().GetResponseStream())
cls.CreateCSVTable(strReader.ReadLine())
While (InlineAssignHelper(SingleLine, strReader.ReadLine())) IsNot Nothing
cls.AddRowCSVTable(SingleLine)
End While
GridView1.DataSource = cls.CSVTable
GridView1.DataBind()
If strReader IsNot Nothing Then
strReader.Close()
End If
End If
Catch ex As System.Net.WebException
MsgBox(ex.ToString)
End Try
End Sub
Public Sub CreateCSVTable(ByVal TableColumnsList As String)
CSVTable = New DataTable("CSVTable")
Dim myDataColumn As DataColumn
Dim ColumnName As String() = TableColumnsList.Split(",")
For i As Integer = 0 To ColumnName.Length - 2
myDataColumn = New DataColumn()
myDataColumn.DataType = Type.GetType("System.String")
myDataColumn.ColumnName = ColumnName(i)
CSVTable.Columns.Add(myDataColumn)
Next
End Sub
Public Sub AddRowCSVTable(ByVal RowValueList As String)
Dim RowValue As String() = RowValueList.Split(","c)
Dim myDataRow As DataRow
myDataRow = CSVTable.NewRow()
For i As Integer = 0 To RowValue.Length - 2
myDataRow(i) = RowValue(i)
Next
CSVTable.Rows.Add(myDataRow)
End Sub
The error was "Cannot find column 0" which points on:
myDataRow(i) = RowValue(i)
How can I resolve this error. Thanks in advance.
I have created a sample solution here: Sample Solution
Hope this helps you.

ASP.Net Generate and Save CSV using System.Web.HttpResponse

Hi I'm using the following code to generate a CSV file containing data from a dataset. The CSV generates fine and a prompt box displays so that the user can either open or save the csv file. What I'm wondering is whether it's possible to save the CSV file?
Thanks for any help
Edited with solution (NB I don't need the prompt box to open as I'll be writing additional code to generate and save a number of files and then display links to them). This saves the dataset as a CSV on our server.
Protected Sub exportBtn_click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim ds1 As DataSet
ds1 = csvdownload.ReturnNewPledges()
Dim csv As New chartnew.csvhelper
Dim strData1 As String = csv.Export(ds1, True)
Dim todaydate As Date = Date.Now.Date
Dim todaystr As String = todaydate.ToString("ddMMyyyy")
Dim filename As String = todaystr & "_filename.csv"
Dim saveDir As String = "writedir\files\"
Dim appPath As String = Request.PhysicalApplicationPath
Dim filePath As String = appPath + saveDir + filename
Dim writer As New StreamWriter(filePath)
writer.Write(strData1)
writer.Close()
End Sub
Use a StreamWriter:
Dim SwFromFile As StreamWriter = New StreamWriter(fileName)
SwFromFile.Write(strData1)
SwFromFile.Flush()
SwFromFile.Close()

ASP.NET problem with XSLT transformation

I need help with the following issue. I parse XML and do a XSLT transformation. Everything is fine with Stylus Studio. But with ASP.NET I can't parse and output.
min.aspx.vb
Imports System.Xml
Imports System.Xml.XPath
Imports System.Xml.Xsl
Imports System.IO
Partial Class Poseidon_min
Inherits System.Web.UI.Page
Protected Sub Literal1_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Literal1.PreRender
Dim strXSLTFile As String = "http://www.kiris-alinda.de/Poseidon/Hotelangebote.xslt"
Dim strXMLFile As String = "http://www.kiris-alinda.de/Poseidon/PosXMLReq/PosXMLReqSearch.php?htc=AYTLIND"
Dim reader As XmlReader = XmlReader.Create(strXMLFile)
Dim objXSLTransform As New XslCompiledTransform()
objXSLTransform.Load(strXSLTFile)
Dim htmlOutput As New StringBuilder()
'Dim htmlWriter As TextWriter = New StringWriter(htmlOutput)
'objXSLTransform.Transform(reader, Nothing, htmlWriter)
Me.Literal1.Text = htmlOutput.ToString()
reader.Close()
End Sub
End Class
Why is it not possible to output <xsl:value-of select="PosXmlResponse/search/date/#min"/> from the XSLT in ASP.NET?
Take a look at this :
XML / XSLT Transformation
You have to use an XML Server Control on the ASPX page and then setting up XSLT Transformation
I use this code:
Public Shared Function Transform(xml As String, xsl As String, argsList As XsltArgumentList) As String
Dim selectedXml As XDocument = XDocument.Parse(xml)
Dim xmlTransform As New XslCompiledTransform()
Dim htmlOutput As New StringBuilder()
Dim writer As XmlWriter = XmlWriter.Create(htmlOutput)
xmlTransform.Load(New XmlTextReader(New StringReader(xsl)))
xmlTransform.Transform(selectedXml.CreateReader(), argsList, writer)
Return htmlOutput.ToString()
End Function

Resources