I am unable to export my data into excel.
I have tried the suggestions on S/O, but have not had any luck.
Dim sqlString As String = "spExportRateProfile" & Session("OfficeNumber") & "," & Session("SalesRepID")
Dim conn As SqlConnection = New SqlConnection(Utils.GetConfigKey("ConnectionStringVimas"))
conn.Open()
Dim dt As DataTable = New DataTable()
Dim da As SqlDataAdapter = New SqlDataAdapter(sqlString, conn)
da.Fill(dt)
Response.AddHeader("content-disposition", "attachment;filename=ReportExport.xlsx")
Response.ContentType = "application/vnd.ms-excel"
What do I need do after this to export my data to excel?
You could use a ExcelLibrary like EPPlus(GPL) which i can warmly recommend.
Then it is as easy as this to create Excel-Files from a DataTable and write it to the Response:
Dim pck = New ExcelPackage()
Dim ws = pck.Workbook.Worksheets.Add("Worksheet-Name")
ws.Cells("A1").LoadFromDataTable(dt, True, OfficeOpenXml.Table.TableStyles.Medium1)
Response.Clear()
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
Response.AddHeader("content-disposition", "attachment; filename=ExcelFileName.xlsx")
Response.BinaryWrite(pck.GetAsByteArray())
Here is another example: http://epplus.codeplex.com/wikipage?title=WebapplicationExample
once you have your datatable dt here you should do this (C# - just copied from the Internet)
...
da.Fill(dt);
Response.ContentType = "Application/x-msexcel";
Response.AddHeader("content-disposition", "attachment; filename=\"test.csv\"");
Response.Write((new ExportXMLCSV()).ToCSV(dt));
Response.End();
and here the method ToCSV of the class ExportXMLCSV (C# - just copied from the Internet)
public string ToCSV(DataTable dataTable)
{
//create the stringbuilder that would hold our data
StringBuilder sb = new StringBuilder();
//check if there are columns in our datatable
if (dataTable.Columns.Count != 0)
{
//loop thru each of the columns so that we could build the headers
//for each field in our datatable
foreach (DataColumn column in dataTable.Columns)
{
//append the column name followed by our separator
sb.Append(column.ColumnName + ',');
}
//append a carriage return
sb.Append("\r\n");
//loop thru each row of our datatable
foreach (DataRow row in dataTable.Rows)
{
//loop thru each column in our datatable
foreach (DataColumn column in dataTable.Columns)
{
//get the value for tht row on the specified column
// and append our separator
sb.Append(row[column].ToString() + ',');
}
//append a carriage return
sb.Append("\r\n");
}
}
//return our values
return sb.ToString();
}
everything just copied from here: http://forums.asp.net/t/1115305.aspx you should be good to go with a little exercise of conversion C# -> VB.NET ;-)
Related
I am using ASP.Net and Open office XML and I have been able to set the headers of the excel file.
However, I want to set the value to cells from say D2 to D1000 in a drop down fashion i.e. that the user can only select from a predefined list of values as in a drop down list.
How do I accomplish this?
The code for creating the excel is
List<ExcelExport> mpList = new List<ExcelExport>();
DataTable dt = ListToDataTable(mpList);
string attachment = string.Format("attachment;filename={0}-{1}.xlsx", ddlHealthFacility.SelectedItem.Text + " Excel export ", " ");
using (ExcelPackage pck = new ExcelPackage())
{
//Create the worksheet
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Monthly Plan");
ws.Cells["A1"].LoadFromDataTable(dt, true);
Byte[] fileBytes = pck.GetAsByteArray();
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", attachment);
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
Response.BinaryWrite(fileBytes);
Response.End();
}
Am using the Following Function for Export the Excel File.It Was working Fine.I retrieve the Records from SQL DataBase to data table and I Export the Excel Sheet.
public ActionResult ExporttoExcel()
{
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection("Connection string here");
con.Open();
SqlCommand cmd = new SqlCommand("select * from Exportxcel", con);
dt.Load(cmd.ExecuteReader());
int total = 0;
foreach (DataRow row in dt.Rows)
{
int salaryvalue = Convert.ToInt32(row["Salary"]);
total = salaryvalue + total;
}
dt.Rows.Add(new object[] { "", "Total", total });
if (dt.Rows.Count > 0)
{
string filename = "ExcelExport.xls";
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
DataGrid dgGrid = new DataGrid();
dgGrid.DataSource = dt;
dgGrid.DataBind();
dgGrid.RenderControl(hw);
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
Response.Write(tw.ToString());
Response.End();
}
return View(dt);
}
My question is I need to add Two title before the Value Bind?How to do this?I need to add Title ,author like the following Screen Shot.How to do this?
You could try adding this just after declaring System.Web.UI.HtmlTextWriter hw
hw.Write("<table><tr><td colspan='3'>Title</td></tr>")
hw.Write("<table><tr><td colspan='3'>Author</td></tr>")
I want to export data of DataTable or DataSet with formating like Color of Header-Footer, Font Size, Row Color in Word, Excel and PDF format. Is it possible?
If yes then how? Please healp me.
My code is as below.
public void ExportToExcel(DataTable dt)
{
con.Open();
string sql = "select *from test";
cmd = new SqlCommand(sql, con);
dt = new DataTable();
da = new SqlDataAdapter(cmd);
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
cmd.Dispose();
string filename = "DownloadTest.xls";
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
DataGrid dgGrid = new DataGrid();
dgGrid.DataSource = dt;
dgGrid.DataBind();
DataSet ds = new DataSet();
ds = dt.Clone;
dgGrid.RenderControl(hw);
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
this.EnableViewState = false;
Response.Write(tw.ToString());
Response.End();
con.Close();
}
for pdf :-
I think you should use 'itextSharp'. You can go through this link http://www.codeproject.com/Articles/81118/ITextSharp-Helper-Class
You can download it (.dll) from here
http://sourceforge.net/projects/itextsharp/
For excel and word you can use gridview to export it to excel and word with color and fonts.
for excel you can go through this link
I am trying to retrieve a list of the worksheets in an Excel workbook, but the collection I get back has both the sheet names and the data column id's, which seem to be called 'Defined Names' in the original xlsx xml. Can you tell me how to return only the worksheet names?
The code I'm using is along the lines of:
OleDbConnection connExcel = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;"
+ #"Data Source=" + FilePath + ";"
+ #"Extended Properties=""Excel 8.0;HDR=Yes;""");
OleDbCommand cmdExcel = new OleDbCommand();
cmdExcel.Connection = connExcel;
connExcel.Open();
DataTable testTable = connExcel.GetSchema("Tables");
The contents of the resulting testTable collection contain entries under TABLE_NAME of:
DATA1
DATA2
DATA3
DATA4
DATA5
Sheet1$
TEST1
-TEST2
TESTHKEY
TESTKEYS
TESTVKEY
They all have a TABLE_TYPE of TABLE.
The original workbook corresponding to the above would have 1 worksheet containing 5 columns, the first row would contain a header. I'm only interested in the Sheet1$ entry. The spreadsheet is
created in Excel 2010, I'm trying to process it in an ASP.NET 4 app written in C#. Potentially, the worksheet name may have been changed so I can't guarrantee that it will always be Sheet1$.
My first thoughts were wrong so I came up with this as a workaround. The actual worksheet names returned should always end with $, so I hacked it to check for that. Messy but you get the general idea I'm sure.
OleDbConnection connExcel = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;"
+ #"Data Source=c:\test.xlsx;"
+ #"Extended Properties=""Excel 12.0 Xml;HDR=Yes;""");
OleDbCommand cmdExcel = new OleDbCommand();
cmdExcel.Connection = connExcel;
connExcel.Open();
DataTable testTable = connExcel.GetSchema("Tables");
String[] excelSheets = new String[testTable.Rows.Count];
int i = 0;
foreach (DataRow row in testTable.Rows)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
if (excelSheets[i].EndsWith("$"))
{
Console.WriteLine(excelSheets[i] = row["TABLE_NAME"].ToString());
i++;
}
else
{
i++;
}
}
Console.ReadLine();
I had a similar issue but with the exception that it showed me Sheets that didn't exist in Excel. Even though this post is a bit old now, maybe somebody finds this and finds it helpful.
My Code:
//OpenFileDialog
try
{
OpenFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
OpenFileDialog.Filter = "XLSX Files(*.xlsx)|*.xlsx|All Files (*.*)|*.*";
OpenFileDialog.ShowDialog();
}
catch (Exception ex)
{
//some Error Message
}
//read into Combobox
try
{
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + OpenFileDialog.FileName + ";Extended Properties=Excel 12.0;");
con.Open();
DataTable dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
con.Close();
this.Combobox.Items.Clear();
for (int i = 0; i < dt.Rows.Count; i++)
{
String sheetName = dt.Rows[i]["TABLE_NAME"].ToString();
sheetName = sheetName.Substring(0, sheetName.Length - 1);
//cheap Filter to filter out unneeded/wrong sheets
if (sheetName.Replace("'", " ").Replace("$", " ").TrimStart().TrimEnd().Contains("#") != true)
{
this.Combobox.Items.Add(sheetName.Replace("'", " ").Replace("$", " ").TrimStart().TrimEnd());
}
}
}
catch (Exception Ex)
{
//some Error Message
}
This might not be the best solution, but it works quite well for me.
private static string EXCEL_CONNECTIONSTRING = string.Format("Provider=Microsoft.ACE.OLEDB.12.0; data source={0}; Extended Properties=Excel 12.0;", "#{FILENAME}");
private IEnumerable<string> GetWorksheetNames(string excelFile)
{
var currentConnectionString = EXCEL_CONNECTIONSTRING.Replace("#{FILENAME}", excelFile);
using (OleDbConnection connection = new OleDbConnection(currentConnectionString))
{
OleDbCommand cmdExcel = new OleDbCommand();
cmdExcel.Connection = connection;
connection.Open();
DataTable dt = connection.GetSchema("Tables");
IEnumerable<string> excelSheets = dt.Rows.Cast<DataRow>().Select(row => row["TABLE_NAME"].ToString());
dt.Dispose();
connection.Close();
return excelSheets;
}
}
I am trying to read datas from an uploaded xls. I have used this code part:
OleDbConnection connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath(fileName) + ";Extended Properties=Excel 8.0");
if (connection.State == ConnectionState.Closed)
connection.Open();
string query = "select * from [Sheet1$]";
OleDbDataAdapter da = new OleDbDataAdapter(query, connection);
DataSet ds = new DataSet();
da.Fill(ds);
But I get this error: External table is not in the expected format.
I am pretty sure I am giving the correct path. I was working and it is not. if it works then it wont fill the datatable. It gives an error that says that Sheet1$ object can not be found. Any help?
are you sure the excel version is correct? you may also want to wrap the extended properties in quotes as well. I would also recommend cleaning up your resources so you don't create memory leaks.
var path = Server.MapPath(fileName);
//where 8.0 may be a different version: 9 - 12?
var connectionString = string.Format(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended ""Properties=Excel 8.0""", path);
using(var connection = new OleDbConnection(connectionString))
using(var command = connection.CreateCommand())
{
connection.Open();
command.CommandText = "select * from [Sheet1$]";
var table = new DataTable();
using(var reader = command.ExeucteReader())
{
table.Load(reader);
return table;
}
}
Have a look at this thread:
Excel "External table is not in the expected format."
Maybe you should change provider as they suggest.
One other option is to use the OpenXML SDK to read the excel file. This could get you started:
http://msdn.microsoft.com/en-us/library/ff921204.aspx
string savePath = "/Assets/UploadedFiles/";
string fileName = "Activity.xls";
savePath += fileName;
OleDbConnection conn= new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Server.MapPath(savePath) + ";Extended Properties='Excel 12.0;HDR=YES'");
if (conn.State == ConnectionState.Closed)
conn.Open();
string query = "select * from [Sheet1$]";
OleDbDataAdapter da = new OleDbDataAdapter(query, conn);
DataSet ds = new DataSet();
da.Fill(ds, "Activities");
dt = ds.Tables[0];
conn.Close();
save the file in the hard disk, then add a reference to Microsoft Excel 12.0 Object Library and declare the using:
using Excel = Microsoft.Office.Interop.Excel;
then instantiate a class and load the file to read the cell values, example:
Excel.Application xlApp ;
Excel.Workbook xlWorkBook ;
Excel.Worksheet xlWorkSheet ;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Open("file.xls", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
MessageBox.Show(xlWorkSheet.get_Range("A1","A1").Value2.ToString());
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
EDIT 1:
If you don't want to install Office in the server, you can use the excellibrary that works similar, simple as (from the author page) :
// open xls file
Workbook book = Workbook.Load(file);
Worksheet sheet = book.Worksheets[0];
// traverse cells
foreach (Pair<Pair<int, int>, Cell> cell in sheet.Cells)
{
dgvCells[cell.Left.Right, cell.Left.Left].Value = cell.Right.Value;
}
// traverse rows by Index
for (int rowIndex = sheet.Cells.FirstRowIndex;
rowIndex <= sheet.Cells.LastRowIndex; rowIndex++)
{
Row row = sheet.Cells.GetRow(rowIndex);
for (int colIndex = row.FirstColIndex;
colIndex <= row.LastColIndex; colIndex++)
{
Cell cell = row.GetCell(colIndex);
}
}