Friday, January 15, 2010
Import from Excel Sheet into Sql Table with filtering
Monday, January 12, 2009
How to export GridView to PDF (ASP.NET)
How to export GridView to PDF (ASP.NET)
Recently I have been trying to generate some reports to PDF file format from ASP. NET2.0 application. There are a lot of open source PDF libraries out there that you can use to export to PDF such as iTextSharp, Gios PDF .NET Library and PDFSharp. You can go to this link to find out more open source PDF libraries in C#.
Later I will show you a working solution on how to export GridView to PDF by using one of the free libraries – iTextSharp.
ITextSharp is a port of the iText open source java library written entirely in C# for the .NET platform. It is a library that allows developers to extend the capabilities of their web server applications with dynamic PDF document generation and generate PDF file on the fly.
Before that, you need to download the iTextSharp library. Here is the download link.
Add in the iTextSharp.dll as a reference into your web application.
Here is my sample of code:…
using iTextSharp.text;
using iTextSharp.text.pdf;
protected void Page_Load(object sender, EventArgs e)
{
ExportToPDF();
}
private void ExportToPDF()
{
Document document = new Document(PageSize.A4, 0, 0, 50, 50);
System.IO.MemoryStream msReport = newSystem.IO.MemoryStream();
try {
// creation of the different writers
PdfWriter writer = PdfWriter.GetInstance(document, msReport);
// we add some meta information to the document
document.AddAuthor("eJuly");
document.AddSubject("Export to PDF");
document.Open();
iTextSharp.text.Table datatable = new iTextSharp.text.Table(7);
datatable.Padding = 2;
datatable.Spacing = 0;
float[] headerwidths = { 6, 20, 32, 18, 8, 8, 8 };
datatable.Widths = headerwidths;
// the first cell spans 7 columns
Cell cell = new Cell(new Phrase("System Users Report",FontFactory.GetFont(FontFactory.HELVETICA, 16,Font.BOLD)));
cell.HorizontalAlignment = Element.ALIGN_CENTER;
cell.Leading = 30;
cell.Colspan = 7;
cell.Border = Rectangle.NO_BORDER;
cell.BackgroundColor = newiTextSharp.text.Color(System.Drawing.Color.Gray);
datatable.AddCell(cell);
// These cells span 2 rows
datatable.DefaultCellBorderWidth = 1;
datatable.DefaultHorizontalAlignment = 1;
datatable.DefaultRowspan = 2;
datatable.AddCell("No.");
datatable.AddCell(new Phrase("Full Name",FontFactory.GetFont(FontFactory.HELVETICA, 14,Font.NORMAL)));
datatable.AddCell("Address");
datatable.AddCell("Telephone No.");
// This cell spans the remaining 3 columns in 1 row
datatable.DefaultRowspan = 1;
datatable.DefaultColspan = 3;
datatable.AddCell("Just Put Anything");
// These cells span 1 row and 1 column
datatable.DefaultColspan = 1;
datatable.AddCell("Col 1");
datatable.AddCell("Col 2");
datatable.AddCell("Col 3");
datatable.DefaultCellBorderWidth = 1;
datatable.DefaultRowspan = 1;
for (int i = 1; i < 20; i++) {
datatable.DefaultHorizontalAlignment =Element.ALIGN_LEFT;
datatable.AddCell(i.ToString());
datatable.AddCell("This is my name.");
datatable.AddCell("I have a very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very long long address.");
datatable.AddCell("0123456789");
datatable.DefaultHorizontalAlignment =Element.ALIGN_CENTER;
datatable.AddCell("No");
datatable.AddCell("Yes");
datatable.AddCell("No");
}
document.Add(datatable);
}
catch (Exception e) {
Console.Error.WriteLine(e.Message);
}
// we close the document
document.Close();
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=Export.pdf");
Response.ContentType = "application/pdf";
Response.BinaryWrite(msReport.ToArray());
Response.End();
}
Hope these codes can help those people who are new to asp.net developing and save some time on their searching solutions. You can also find the tutorial of iTextSharp at here.
Import Data from Excel File to sql datatable
Import Data from Excel File to sql datatableTo Export Data Form an Excel file, there is one drawback lying behind them. The Sheet1 from the query actually is the name of the spreadsheet in your excel file. What if there is no Sheet1 inside the excel file? What if you don’t even know the sheet name?
Yes. I found this error when I tried to upload an excel file with different sheet name. And here is the solution for that.
To get the sheet name in your excel file, firstly, Microsoft DAO 3.5 Library is needed. Go to Project -> Reference -> Add Reference, select Microsoft DOA 3.5 Library from the list and add to your project. Here is the example code of how to get the first sheet in the excel file.
Dim strConn As String
Dim da As OleDbDataAdapter
Dim ds As New DataSet
Dim dao_dbE As dao.DBEngine
Dim dao_DB As DAO.Database
Dim strSheet As String
dao_dbE = New dao.DBEngine
dao_DB = dao_dbE.OpenDatabase("C:\test.xls", False, True, "Excel 8.0;")
strSheet = dao_DB.TableDefs(0).Name
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=C:\test.xls;Extended Properties=""Excel 8.0;"""
da = New OleDbDataAdapter("SELECT * FROM [" & _
strSheet & "]", strConn)
da.TableMappings.Add("Table", "Excel")
da.Fill(ds)
Import Data from Excel File to sql datatable
Import Data from Excel File to sql datatable
As I has stated in my previous post regarding to Export Data Form an Excel file, there is one drawback lying behind them. The Sheet1 from the query actually is the name of the spreadsheet in your excel file. What if there is no Sheet1 inside the excel file? What if you don’t even know the sheet name?
Yes. I found this error when I tried to upload an excel file with different sheet name. And here is the solution for that.
To get the sheet name in your excel file, firstly, Microsoft DAO 3.5 Library is needed. Go to Project -> Reference -> Add Reference, select Microsoft DOA 3.5 Library from the list and add to your project. Here is the example code of how to get the first sheet in the excel file.
Dim strConn As String
Dim da As OleDbDataAdapter
Dim ds As New DataSet
Dim dao_dbE As dao.DBEngine
Dim dao_DB As DAO.Database
Dim strSheet As String
dao_dbE = New dao.DBEngine
dao_DB = dao_dbE.OpenDatabase("C:\test.xls", False, True, "Excel 8.0;")
strSheet = dao_DB.TableDefs(0).Name
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=C:\test.xls;Extended Properties=""Excel 8.0;"""
da = New OleDbDataAdapter("SELECT * FROM [" & _
strSheet & "]", strConn)
da.TableMappings.Add("Table", "Excel")
da.Fill(ds)
Export Datatable to Excel
Export Datatable to Excel(Not HTML Tables)
Recently I working with export data to an excel file, but had faced a lot of problems. The main problem of it: The exported file is saved as HTML tables with XLS extension, not the actual XLS format. In this way, I can’t re-import the data using the OleDbConnection.
I have been searching around the net, but no exact solution that suit my situation. Finally, I had found another way to export data into the actual XLS format, by using Excel.Application.
First thing that you need to do is to add Excel dll (Microsoft Excel 11.0 Object Library) as a reference.
Here are the codes.
Private Function ExportToExcel(ByVal dt As System.Data.DataTable)
Dim xlsApp As New Excel.Application
Dim xlsWorkbook As Excel.Workbook
Dim xlsWorksheets As Excel.Worksheets
Dim xlsWorksheet As Excel.Worksheet
Dim strhdr As String
Dim row As Integer
Dim drow As DataRow
Dim strFile As String = "test.xls"
Dim filename As String = Server.MapPath("Doc") & "\" & strFile
If dt.Rows.Count > 0 Then
'Create new workbook
xlsWorkbook =
xlsApp.Workbooks.Add
'Get the first worksheet
xlsWorksheet = CType(xlsWorkbook.Worksheets(1), Excel.Worksheet)
'Activate current worksheet
xlsWorksheet.Activate()
'Set header row to row 1
row = 1
'Add table headers to worksheet
xlsWorksheet.Cells(row,1).Value = "NAME"
xlsWorksheet.Cells(row, 2).Value = "JOB POSITION"
xlsWorksheet.Cells(row, 3).Value = "ORIGIN"
'Format header row (bold, extra row height, autofit
width)
With xlsWorksheet.Range("A" & row, "C" & row)
.Font.Bold = True
.Rows(row).RowHeight = 1.5 * xlsWorksheet.StandardHeight
.EntireRow.AutoFit()
End With
'Freeze the column headers
With xlsWorksheet.Range("A" & row + 1, "C" & row + 1).Select
xlsApp.ActiveWindow.FreezePanes = True
End With
'Write data to Excel worksheet
For Each drow In dt.Rows
row += 1
If Not IsDBNull(dr.Item("NAME")) Then xlsWorksheet.Cells(row, 1).Value = dr.Item("NAME")
If Not IsDBNull(dr.Item("JOB POSITION")) Then xlsWorksheet.Cells(row, 2).Value = dr.Item("JOB POSITION")
If Not IsDBNull(dr.Item("ORIGIN")) Then xlsWorksheet.Cells(row, 3).Value =
dr.Item("ORIGIN")
Next
'Format data rows (align to top, autofit width and height)
With xlsWorksheet.Range("A2", "C" & row)
.VerticalAlignment = CType(XlVAlign.xlVAlignCenter, Excel.XlVAlign)
.HorizontalAlignment = CType(XlHAlign.xlHAlignLeft, Excel.XlHAlign)
.EntireColumn.AutoFit()
.EntireRow.AutoFit()
End With
'Make excel workbook visible to user after all data has been added to worksheet
xlsApp.DisplayAlerts = False
xlsWorkbook.Close(True, filename)
'Export data to client machine
strhdr = "attachment;filename=" & strFile
With Response
.Clear()
.ContentType = "application/vnd.ms-excel"
.ContentEncoding = System.Text.Encoding.Default
.AppendHeader("Content-Disposition", strhdr)
.WriteFile(filename)
.Flush()
.Clear()
.Close()
End With
End If
End Function
Monday, November 3, 2008
Export SQL table to excel
Dim wBook As Excel.Workbook
Dim wSheet As Excel.Worksheet
wBook = excel.Workbooks.Add()
wSheet = wBook.ActiveSheet()
Dim dt As DataGridView = TblJobMethodsDataGridView.DataSource.Tables(0)
Dim dc As System.Data.DataColumn
Dim dr As System.Data.DataRow
Dim colIndex As Integer = 0
Dim rowIndex As Integer = 0
For Each dc In dt.Columns
colIndex = colIndex + 1
excel.Cells(1, colIndex) = dc.ColumnName
Next
For Each dr In dt.Rows
rowIndex = rowIndex + 1
colIndex = 0
For Each dc In dt.Columns
colIndex = colIndex + 1
excel.Cells(rowIndex + 1, colIndex) = dr(dc.ColumnName)
Next
Next
wSheet.Columns.AutoFit()
Dim strFileName As String = "D:\ss.xls"
Dim blnFileOpen As Boolean = False
Try
Dim fileTemp As System.IO.FileStream = System.IO.File.OpenWrite(strFileName)
fileTemp.Close()
Catch ex As Exception
blnFileOpen = False
End Try
If System.IO.File.Exists(strFileName) Then
System.IO.File.Delete(strFileName)
End If
wBook.SaveAs(strFileName)
excel.Workbooks.Open(strFileName)
excel.Visible = True