|
|
Comments and Discussions
|
|
 |

|
Hello,
I tried utilizing your code in a project of mine, but I received the following error after doing the reponse.Flush and response.End
"ex = {Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.}"
Any clue as to why this could be happening? I tried substituting the dataset/datatables you were creating programmatically in place of mine, but I get the same result. Not sure how to overcome this issue.
Update:
Additonally, if I use HttpContext.Current.ApplicationInstance.CompleteRequest() instead Response.End(), I get the following,
"Microsoft JScript runtime error: Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed."
modified 3 hrs ago.
|
|
|
|

|
Why the generated file is not recgnized neiher by the Microsoft.Jet.OLEDB.4.0 nor Microsoft.ACE.OLEDB.12.0?
|
|
|
|

|
Hi,
Your code works pretty fine with little modification. It works fine on client machine. But Instead of opening the excel on client machine, I need to save it on network shared directory.
Could you please help me to achieve this? Or any other link where I can refer to.
Thanks in Advance
jjk
|
|
|
|

|
I tried using your code to export the data in excel. I get "Out of Memory" exception if there is data more than 1 lakhs records.
|
|
|
|

|
hi Ming_lu,
When I run this code in a machine which has Office 2010, it saves the file without the .xls file extension, and when i try to open in office 2010, we get warning message saying that the file is not in the correct format as the file extension.
how to solve this ? and be able to open in 2010 too..
Thanks.
|
|
|
|

|
Thanks For Share this artical very helpful
|
|
|
|

|
Excellent work!! really appreciate it
|
|
|
|

|
i try your code.its fine. but i dont understand because my datagrid is call data from database.select command.so how to display the data.right now you just add value1,value2. my data is depend on what user key in.i cannot write every sngle column and row.
pls help me.i have to submit the project asap :'(
musiw
|
|
|
|

|
Man, this is awesome...Thanks
|
|
|
|

|
Really superb...solved my problem
|
|
|
|

|
I was originally thinking that somehow inserting a page break via response.write would give me a new tab. After much searching it seems that I wouldn't be able to insert a page break via that method.
Your code has assisted me greatly!
Thanks!
|
|
|
|
|

|
Thanks for this helpful code.. it really helped me..
But I am also getting the same issue as reported by ARK Kambhampati
|
|
|
|
|

|
Hello,
Very NICE post.
Im using your sample code without any change, when I save the file test.xls on my desktop and when I open it, I get an error message saying "The file you are trying to open, 'test.xls', is in a different format than specified by the file extension. Verify that the file is not corrupted and is from a trusted source before opening the file. Do you want to open the file now?"
I then click on Yes, and the file in Excel is working perfectly as it should, 2 worksheets are created, with correct rows and columns as coded in your code.
So why do I get this message? Any way to generate an excel file that would avoid getting this error?
Thank you,
Philippe
|
|
|
|

|
It's because you're saving it as a .xls. Change it to .xlsx.
|
|
|
|

|
It still gives the same warning, even when I change the code to save as .xslx
|
|
|
|
|

|
Excellent article. Vote of 5
Can you help with formatting alternate row color & Auto fit.
|
|
|
|
|

|
I get an error when download a file. The ... style\main.css cannot be found. I don't see a reference to that in the example. Where does it reference the file?
This line generates the error
sb.Append("\r\n");
Why do many attribute tags have a leading '\' character?
modified on Friday, August 26, 2011 6:59 PM
|
|
|
|

|
If Iam working with Marquee taq in my webpage , it gives an error. how to solve this problem?
By
P.Muthu raj
tr
|
|
|
|

|
Thanks for sharing!
|
|
|
|

|
I have tried exporting datatables to different worksheets using your code.
It was working fine. Thanks for the post.
But however, I have done some customization on the formatting and your styling. But when I export data, some fields which holds data as Int, but column name as string, is ignores the cases you have posted.
So my excel sheet contains numbers stored as Text, I need to change the format.
Any suggestion to take care of these scenarios, in code.
Thanks,
CodingRocks
ASP.NET,C#.NET Programmer
BANGALORE
"Winners don't do different things. They do things differently. ...
|
|
|
|

|
you can try to use Excel to create the template you need, then the xml output of the template to see how things defined, then produce the xml in the code.
|
|
|
|

|
Its Good One,i got the code ...any how ...thanks you very much
|
|
|
|

|
very useful.
Thanks for posting.
|
|
|
|
|

|
Hi,
there is easier way to export DataSet to Excel with GemBox.Spreadsheet Excel C# library.
Here is a code snippet:
var ef = new ExcelFile();
foreach (DataTable dataTable in dataSet.Tables)
{
var ws = ef.Worksheets.Add(dataTable.TableName);
ws.InsertDataTable(dataTable, "A1", true);
}
ef.SaveXls("DataSet.xls");
|
|
|
|

|
I am new to Asp.net & tried ur code,i found it excellent, i had a hurdle & could not fix AutoFit in my columns using your code in my worksheets. please give some suggestion.
CAUCASIAN KNIVES
|
|
|
|

|
I am exporting numerous dataset tables (upwards of 30 to 40 tabs) into a excel spreadsheet. I keep returning this error
Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed. Common causes for this error are when the response is modified by calls to Response.Write(), response filters, HttpModules, or server trace is enabled. Details Error parsing near '<xml version>
<Work'.
I have researched the error in great depth and nothing seems to remedy the problem. I am not sure if the problem is in the size of my export, in the UpdatePanels inability to redraw the previously viewed data because of the AsyncPostback, or is it crapping out trying to write the XML for the export. I am at a total loss. Please help, any insight would be greatly valued.
Steve C
|
|
|
|

|
One way to pin point the problem in your case is to save the httpresponse (that is the content of Response.Write()) in xml format and open it with excel, or notepad to see if the xml file is well formed or not.
Anther thing you can try is replacing the update panel with a regular asp.net panel to sort out the possibility of updatepanel doing weird things.
|
|
|
|

|
Thanks for the direction on this, I removed the update panel and it does seem to be the culprit. Do you have any words of wisdom on how to manage this issue within the UpdatePanel. Since you used the term "weird things" it would lead me to believe that the issue may be a bit ellusive with the fix more difficult to determine. Any path on which way to proceed would be greatly appreciated.
Steve
|
|
|
|

|
What shd i use instead of var??
|
|
|
|

|
The excel file generated for 65536 rows data (2 sheets) is about 64MB..that's too much..before using the xml method, it consumes around 5MB only. any solutions?
|
|
|
|

|
I need to export a table data to excel with insert comments as we have comments in Excel.I tried adding
<Comment><ss:Data>\"Hello World\"</ss:Data></Comment>
to the getcell function in your project, but it did not work.
Please help!!!
modified on Wednesday, June 17, 2009 8:12 AM
|
|
|
|

|
Hi
is there a way to handle linie feeds inside cells?
|
|
|
|

|
By modifying the Table tag to <Table ss:ExpandedColumnCount="2" ss:ExpandedRowCount="2" x:FullColumns="1"
x:FullRows="1" ss:DefaultRowHeight="15">
you can control the line feeds.
|
|
|
|

|
Dear Ming_Lu
I can't get the linefeed feature to work,
Is it possible for you to upgrade the sample project to include a cell with a linefeed.
Thanks in avance
Regards Claus
|
|
|
|

|
Hi,
Can I use this class in Windows Application? Please let me know ASAP. Thanks for sharing.
Thanks & Best Regards
Su Win
|
|
|
|

|
You should be to use in the windows application by the changing the "HttpResponse" type to some "Stream" Type such as MemoryStream.
|
|
|
|
|

|
kindly send me code if u are done with this appication for windows application as i am facing lots of errors
|
|
|
|

|
I did it but i was not using this method. If you want other ways, May I know ur email address? Pls give me ur email.
|
|
|
|

|
hi,
I need the solution in the windows aplication.So please mail me the source code to chozhanvijay@gmail.com.
Thanks in Advance
Vijay
|
|
|
|

|
I already send to you. thanks.
see below my coding
using Microsoft.Office.Core; using Excels = Microsoft.Office.Interop.Excel; namespace ImportExportApp.Classes
{
class ImportExport : IDisposable
{
#region variables
string sqlConnStr = String.Empty;
DBManager _dbManager;
int rowLimit = 10000;
string excelVersion = "8.0";
Hashtable myHashtable;
public string message = string.Empty;
#endregion
public ImportExport()
{
_dbManager = new DBManager(_loginID, _SCID);
rowLimit = Convert.ToInt32(ConfigurationManager.AppSettings["rowLimit"].ToString());
excelVersion = ConfigurationManager.AppSettings["excelVersion"].ToString().Trim();
}
private string GetExcelConStr(string fileName)
{
string result = @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + fileName + @";Extended Properties=""Excel 8.0;HDR=NO;IMEX=1""";
if (excelVersion != "8.0")
result = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + @";Extended Properties=""Excel 12.0;HDR=NO;IMEX=1"";";
return result;
}
#region Import Excel Data To SQL Server
public void ImportExcelData(string fileName)
{
DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb");
string excelConStr = this.GetExcelConStr(fileName);
DbDataAdapter adapter = factory.CreateDataAdapter();
DbCommand selectCommand = factory.CreateCommand();
DbConnection connection = factory.CreateConnection();
DataSet ds = new DataSet();
DataTable dt = new DataTable();
int totalRecords = 0;
int successfulRecords = 0;
int errorRecords = 0;
int duplicateRecords = 0;
try
{
if (fileName != null && fileName != "")
{
#region GetListOfWorkSheets
DataTable sheets = new DataTable();
sheets = this.GetWorkSheets(fileName);
#endregion
#region Retrieve from ExcelWorkSheets
foreach (DataRow sheet in sheets.Rows)
{
string sheetName = sheet["TABLE_NAME"].ToString();
selectCommand.CommandText = "SELECT * FROM [" + sheetName + "]";
if (dt != null) dt = null;
dt = new DataTable();
connection.ConnectionString = excelConStr;
selectCommand.Connection = connection;
adapter.SelectCommand = selectCommand;
adapter.Fill(dt);
if (dt.Rows.Count >= 1)
{
if (!string.IsNullOrEmpty(dt.Rows[0][0].ToString()))
{
totalRecords += dt.Rows.Count-1;
this.WriteDataToSQL(dt, sheetName, ref errorRecords, ref successfulRecords, ref totalRecords, ref duplicateRecords);
}
}
}
if (sheets.Rows.Count>=0)
this.WriteMessage(totalRecords, successfulRecords, errorRecords, duplicateRecords);
if (sheets != null) sheets.Dispose();
#endregion
}
}
catch (Exception ex)
{
}
finally
{
if (factory != null) factory = null;
excelConStr = null;
if (adapter != null) adapter.Dispose();
if (selectCommand != null) selectCommand.Dispose();
if (connection != null) connection.Dispose();
if (ds != null) ds.Dispose();
if (dt != null) dt.Dispose();
totalRecords = 0;
successfulRecords = 0;
errorRecords = 0;
duplicateRecords = 0;
if (_dbManager != null) { _dbManager.Dispose(); _dbManager = null; }
}
}
private void WriteDataToSQL(DataTable dt, string sheetName, ref int errorRecords, ref int successfulRecords, ref int totalRecords, ref int duplicateRecords)
{
#region Variables
string ID = String.Empty;
int AccessID = 0;
string PassNo = String.Empty;
string NRIC = String.Empty;
string Name = String.Empty;
int CompanyID = 0;
string Nationality = String.Empty;
string Race = String.Empty;
string Country = String.Empty;
string State = String.Empty;
string PostalCode = String.Empty;
string _address = String.Empty;
string _gender = "G";
string _dOB = String.Empty;
byte[] _photo = null;
bool _gTFlag = false;
#endregion
#region For Loop
for (int row = 1; row < dt.Rows.Count; row++)
{ try{
inputData = String.Empty;
activeData = String.Empty;
ID = dt.Rows[row][0].ToString().Trim().Replace("'", "");
if (String.IsNullOrEmpty(dt.Rows[row][1].ToString()) == false)
AccessID = Convert.ToInt32(dt.Rows[row][1].ToString());
PassNo = CheckStringIsNullOrEmptyReturnString(dt.Rows[row][2].ToString());
NRIC = CheckStringIsNullOrEmptyReturnString(dt.Rows[row][3].ToString());
Name = CheckStringIsNullOrEmptyReturnString(dt.Rows[row][4].ToString());
if (String.IsNullOrEmpty(dt.Rows[row][5].ToString()) == false)
char outputChar = '0';
Nationality = CheckStringIsNullOrEmptyReturnString(dt.Rows[row][6].ToString());
Race = CheckStringIsNullOrEmptyReturnString(dt.Rows[row][7].ToString());
Country = CheckStringIsNullOrEmptyReturnString(dt.Rows[row][8].ToString());
State = CheckStringIsNullOrEmptyReturnString(dt.Rows[row][9].ToString());
PostalCode = CheckStringIsNullOrEmptyReturnString(dt.Rows[row][10].ToString());
_address = CheckStringIsNullOrEmptyReturnString(dt.Rows[row][11].ToString());
_gender = CheckStringIsNullOrEmptyReturnString(dt.Rows[row][12].ToString()).ToUpper();
if (_gender != null && _gender != "")
{
if (_gender.Length > 1)
{
if (_gender.StartsWith("M"))
_gender = "M"; else if (_gender.StartsWith("F"))
_gender = "F"; else if (_gender.StartsWith("G"))
_gender = "G"; else _gender = "A";
}
}
_dOB = CheckStringIsNullOrEmptyReturnString(dt.Rows[row][13].ToString());
photoPath = dt.Rows[row][24].ToString();
_photo = Utilities.GetImageFromFile(photoPath);
int result = 0;
string output = "0";
string outputResult = String.Empty;
result = _dbManager.ImportCAUUser(ID, AccessID, PassNo, NRIC, Name, CompanyID, Nationality, Race, Country, State, _address, PostalCode, _gender, _dOB, _photo, "0", ref output);
#region Clear Variables
ID = String.Empty;
AccessID = 0;
PassNo = String.Empty;
NRIC = String.Empty;
Name = String.Empty;
CompanyID = 0;
Nationality = String.Empty;
Race = String.Empty;
Country = String.Empty;
State = String.Empty;
PostalCode = String.Empty;
_address = String.Empty;
_gender = "O";
_dOB = String.Empty;
#endregion
}
catch (Exception forEx)
{
}
}
#endregion
}
private DataTable GetWorkSheets(string fileName)
{
CheckExcellProcesses();
string conStr = GetExcelConStr(fileName);
DataSet excelData = new DataSet();
OleDbConnection con = new OleDbConnection(conStr);
con.Open();
DataTable sheets = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { });
con.Close();
KillExcel();
if (excelData != null) excelData.Dispose();
if (con != null) con.Dispose();
return sheets;
}
#endregion
#region Export SQL Data To Excel Format
public void ExportSQLDataToExcelFormat(string fileName, string path, string imageFilePath)
{
CheckExcellProcesses();
Excels.Application xlsApp = null;
Excels.Workbook xlsWorkBook = null;
Excels.Worksheet xlsWorkSheet = null;
object oMissing = System.Reflection.Missing.Value;
DataSet ds = new DataSet();
int totalRows = 0;
int index = 1;
short j = 1;
try
{
#region Excel File Location
string[] tmpFileName = fileName.Trim().Split(new char[] { '.' }, 1);
fileName = tmpFileName[0];
if (fileName.Contains(".xls") == false)
fileName = fileName + ".xls";
if (path.EndsWith("\\") == false)
path = path + "\\";
if (File.Exists(path + fileName))
{
if (fileName.EndsWith(".xls") == true)
fileName = fileName.Remove(fileName.Length - 4, 4);
fileName = fileName + "_" + DateTime.Today.ToString("ddMMyyyy") + ".xls";
}
#endregion
#region CreateExcelApplication
try
{
//create excel application
xlsApp = new Excels.Application();
xlsApp.DisplayAlerts = false;
//create new workbook
xlsWorkBook = xlsApp.Workbooks.Add(true);
//Excels.Worksheets xlsWorksheets ;
//xlsWorkSheet = new Excels.Worksheet();
//Add a worksheet to the workbook.
xlsWorkSheet = (Excels.Worksheet)xlsApp.Worksheets.Add(oMissing, oMissing, oMissing, oMissing);
//Name the sheet
xlsWorkSheet.Name = "Sheet_" + j;
j++;
////Get a reference to the first sheet of the workbook.
//xlsWorkSheet = (Excels.Worksheet)xlsWorkBook.Worksheets.get_Item(1);
//Activate current worksheet
//xlsWorkSheet.Activate();
((Excels._Worksheet)xlsWorkSheet).Activate();
}
catch (Exception eee)
{
message = "Export Failed.";
message += "\n\n\n";
message += eee.Message.ToString();
}
#endregion
ds = _dbManager.GetUserList();
totalRows = ds.Tables[0].Rows.Count;
#endregion
//Write Column Name in Excel
this.WriteColumnNameInExcelWorkSheet( xlsWorkSheet);
//Format header row (bold, extra row height, autofit width)
this.FormatHeaderRowInExcelWorkSheet(xlsWorkSheet, xlsApp);
#region Write Data To Excel File
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
index++;
if (index <= rowLimit + 1)
{
//do your insert
this.WriteDataToExcelWorkSheet(imageFilePath, ds.Tables[0].Rows[i], index, xlsWorkSheet);
}
else
{
// create a new worksheet and do your insert here
//Add a worksheet to the workbook.
xlsWorkSheet = (Excels.Worksheet)xlsApp.Worksheets.Add(oMissing, oMissing, oMissing, oMissing);
//Name the sheet
xlsWorkSheet.Name = "Sheet_" + j;
j++;
//Activate current worksheet
//xlsWorkSheet.Activate();
((Excels._Worksheet)xlsWorkSheet).Activate();
this.WriteColumnNameInExcelWorkSheet(xlsWorkSheet);
this.FormatHeaderRowInExcelWorkSheet(xlsWorkSheet, xlsApp);
index = 2;
this.WriteDataToExcelWorkSheet(imageFilePath, ds.Tables[0].Rows[i], index, xlsWorkSheet);
}
}
#endregion
//FormatDataRowsInExcelWorkSheet
this.FormatDataRowsInExcelWorkSheet(xlsWorkSheet, index);
#region Make excel workbook visible to user after all data has been added to worksheet
try
{
xlsApp.DisplayAlerts = false;
xlsWorkBook.Close(true, path + fileName, null);
log.AuditLogActivity(Log.AccessType.CAUUser.ToString(), Log.ActionType.Export.ToString(), "Export User Completed. Total records exported : " + totalRows.ToString(), "", _loginID, _SCID);
message = "Export Completed.";
message += "\n\n\n";
message += "Total records exported : " + totalRows.ToString() + "\n\n";
}
catch (Exception ee)
{
}
#endregion
#region Export data to client machine
//strhdr = "attachment;filename=" + strFile;
//Response.Clear();
//Response.ContentType = "application/vnd.ms-excel";
//Response.ContentEncoding = System.Text.Encoding.Default;
//Response.AppendHeader("Content-Disposition", strhdr);
//Response.WriteFile(filename);
//Response.Flush();
//Response.Clear();
//Response.Close();
#endregion
}
catch (Exception ex)
{
}
finally
{
// kill the right process after export completed
KillExcel();
try
{
if (xlsApp != null)
{
xlsApp.Quit();
xlsApp = null;
}
if (xlsWorkBook != null) xlsWorkBook = null;
if (xlsWorkSheet != null) xlsWorkSheet = null;
if (ds != null) ds = null;
if (oMissing != null) oMissing = null;
}
catch { }
if (_dbManager != null) { _dbManager.Dispose(); _dbManager = null; }
}
}
private void CheckExcellProcesses()
{
Process[] AllProcesses = Process.GetProcessesByName("excel");
myHashtable = new Hashtable();
int iCount = 0;
foreach (Process ExcelProcess in AllProcesses)
{
myHashtable.Add(ExcelProcess.Id, iCount);
iCount = iCount + 1;
}
if (AllProcesses != null) { AllProcesses = null; }
}
private void KillExcel()
{
Process[] AllProcesses = Process.GetProcessesByName("EXCEL");
// check to kill the right process
foreach (Process ExcelProcess in AllProcesses)
{
if (myHashtable.ContainsKey(ExcelProcess.Id) == false)
ExcelProcess.Kill();
}
if (AllProcesses != null) { AllProcesses = null; }
}
#region Write Column Name in Excel WorkSheet
private void WriteColumnNameInExcelWorkSheet(Excels.Worksheet xlsWorkSheet)
{
try
{
//Add table headers to worksheet
xlsWorkSheet.Cells[1, 1] = "ID";
xlsWorkSheet.Cells[1, 2] = "AccessID";
xlsWorkSheet.Cells[1, 3] = "CSN";
xlsWorkSheet.Cells[1, 4] = "NRIC";
xlsWorkSheet.Cells[1, 5] = "Name";
xlsWorkSheet.Cells[1, 6] = "Company Name";
xlsWorkSheet.Cells[1, 7] = "Nationality";
xlsWorkSheet.Cells[1, 8] = "Race";
xlsWorkSheet.Cells[1, 9] = "Country";
xlsWorkSheet.Cells[1, 10] = "State";
xlsWorkSheet.Cells[1, 11] = "Postal Code";
xlsWorkSheet.Cells[1, 12] = "Address";
xlsWorkSheet.Cells[1, 13] = "Gender";
xlsWorkSheet.Cells[1, 14] = "DOB";
xlsWorkSheet.Cells[1, 15] = "Photo";
}
catch (Exception e1){ }
}
#endregion
#region Format header row (bold, extra row height, autofit width)
private void FormatHeaderRowInExcelWorkSheet(Excels.Worksheet xlsWorkSheet, Excels.Application xlsApp)
{
xlsWorkSheet.get_Range("A1", "BA1").Font.Bold = true;
xlsWorkSheet.get_Range("A1", "BA1").Rows.RowHeight = 1.5 * xlsWorkSheet.StandardHeight;
xlsWorkSheet.get_Range("A1", "BA1").EntireRow.AutoFit();
//Freeze the columm headers
xlsWorkSheet.get_Range("A2", "BA2").Select();
xlsApp.ActiveWindow.FreezePanes = true;
}
#endregion
#region Write data to Excel worksheet
private void WriteDataToExcelWorkSheet(string imageFilePath, DataRow dr, int index, Excels.Worksheet xlsWorkSheet)
{
try
{
string ID = null;
if (!Convert.IsDBNull(dr[0])) ID = dr[0].ToString().Trim();
xlsWorkSheet.Cells[index, 1] = "'" + ID;
if (!Convert.IsDBNull(dr[1])) xlsWorkSheet.Cells[index, 2] = dr[1];
if (!Convert.IsDBNull(dr[2])) xlsWorkSheet.Cells[index, 3] = dr[2].ToString().Trim();
if (!Convert.IsDBNull(dr[3])) xlsWorkSheet.Cells[index, 4] = dr[3].ToString().Trim();
if (!Convert.IsDBNull(dr[4])) xlsWorkSheet.Cells[index, 5] = dr[4].ToString().Trim();
//for CompanyID
if (!Convert.IsDBNull(dr[5])) //xlsWorkSheet.Cells[index, 6] = dr[5].ToString().Trim();
xlsWorkSheet.Cells[index, 6] = _dbManager.GetCompanyNameByID(dr[5].ToString().Trim());
if (!Convert.IsDBNull(dr[6])) xlsWorkSheet.Cells[index, 7] = dr[6].ToString().Trim();
if (!Convert.IsDBNull(dr[7])) xlsWorkSheet.Cells[index, 8] = dr[7].ToString().Trim();
if (!Convert.IsDBNull(dr[8])) xlsWorkSheet.Cells[index, 9] = dr[8].ToString().Trim();
if (!Convert.IsDBNull(dr[9])) xlsWorkSheet.Cells[index, 10] = dr[9].ToString().Trim();
if (!Convert.IsDBNull(dr[10])) xlsWorkSheet.Cells[index, 11] = dr[10].ToString().Trim();
if (!Convert.IsDBNull(dr[11])) xlsWorkSheet.Cells[index, 12] = dr[11].ToString().Trim();
//For Gender
if (!Convert.IsDBNull(dr[12]))
{
string gender = dr[12].ToString().Trim().ToUpper();
switch (gender)
{
case "F":
xlsWorkSheet.Cells[index, 13] = "Female";
gender = null;
break;
case "M":
xlsWorkSheet.Cells[index, 13] = "Male";
gender = null;
break;
case "G":
xlsWorkSheet.Cells[index, 13] = "All";
gender = null;
break;
default:
xlsWorkSheet.Cells[index, 13] = "General";
gender = null;
break;
}
}
if (!Convert.IsDBNull(dr[13])) xlsWorkSheet.Cells[index, 14] = dr[13];
if (!Convert.IsDBNull(dr[14])) xlsWorkSheet.Cells[index, 15] = dr[14].ToString().Trim();
#region for Photo
try
{
byte[] imageByte = null;
if (!Convert.IsDBNull(dr[24]))
{
//imageByte = dr[24].GetSqlBytes(24).Value;
imageByte = (byte[])dr[24];
//save the image to imageFileLocation
string imgFileName = imageFilePath + cardID.ToString() + "_Photo.png";
//Image image = Utilities.GetImageFromDB(imageByte);
////image.Save(imgFileName, System.Drawing.Imaging.ImageFormat.Jpeg);
//image.Save(imgFileName);
Bitmap bmp = Utilities.GetImageFromDB(imageByte);
bmp.Save(imgFileName, System.Drawing.Imaging.ImageFormat.Png);
bmp.Dispose();
xlsWorkSheet.Cells[index, 15] = imgFileName; //dr[0].GetSqlBytes(24).Value;
imageByte = null;
if (bmp !=null) bmp = null;
imgFileName = null;
}
}
catch (Exception photoEx){ }
#endregion
}
catch (Exception e) { }
}
#endregion
#region Format data rows (align to center and left, autofit width and height)
private void FormatDataRowsInExcelWorkSheet(Excels.Worksheet xlsWorkSheet, int index)
{
xlsWorkSheet.get_Range("A1", "BA" + index.ToString()).VerticalAlignment = Excels.XlVAlign.xlVAlignCenter;
xlsWorkSheet.get_Range("A1", "BA" + index.ToString()).HorizontalAlignment = Excels.XlHAlign.xlHAlignLeft;
xlsWorkSheet.get_Range("A1", "BA" + index.ToString()).EntireColumn.AutoFit();
xlsWorkSheet.get_Range("A1", "BA" + index.ToString()).EntireRow.AutoFit();
}
#endregion
#endregion
#region Write the Error record into Error log
public void WriteToErrorLogFile(string fileName, string inputLogFile, string inputData)
{
string errorFile = errorFolder + fileName + ".err";// "ImportUser.err";
StreamWriter swError = new StreamWriter(@errorFile, true);
swError.WriteLine(inputLogFile);
swError.WriteLine(inputData);
swError.WriteLine(" ");
swError.Flush();
swError.Close();
}
#endregion
#region Write the successful record into activity log
public void WriteToAcitvityLogFile(string fileName, string inputData)
{
string logFile = activeFolder + fileName + ".log";
StreamWriter swError1;
swError1 = new StreamWriter(@logFile, true);
swError1.WriteLine(inputData);
swError1.WriteLine(" ");
swError1.Flush();
swError1.Close();
}
#endregion
#region Validation
private int CheckStringIsNullOrEmpty(string str)
{
int result = 0;
if (String.IsNullOrEmpty(str) == false)
result = Convert.ToInt32(str);
return result;
}
private string CheckStringIsNullOrEmptyReturnString(string str)
{
string result =String.Empty ;
if (String.IsNullOrEmpty(str) == false)
result = Convert.ToString(str).Trim().Replace("'","`");
return result;
}
private bool CheckStringIsNullOrEmptyReturnBool(string str)
{
bool result = false;
if (String.IsNullOrEmpty(str) == false)
result = Convert.ToBoolean(str);
return result;
}
#endregion
#region IDisposable Members
/// <summary>
/// Dispose Method
/// </summary>
public void Dispose()
{
sqlConnStr = String.Empty;
if (_dbManager != null) {_dbManager.Dispose(); _dbManager=null;}
if (debug != null) {debug.Dispose(); debug =null;}
if (log != null) { log.Dispose(); log = null; }
folderPath = String.Empty;
errorFolder = String.Empty;
activeFolder = String.Empty;
rowLimit = 0;
//workSheetName = null;
if (myHashtable != null) myHashtable = null;
}
#endregion
}
}
|
|
|
|

|
i need that code for win form
|
|
|
|

|
You offered me cool codes to meet my situation. thanks!
But this codes often makes an OutOfMemory exception, as you mentioned, so I altered your codes like this :
private static string getWorksheet(DataTable dt, int index, int cntToProceed)
{
var sw = new StringWriter();
if (dt == null)
{
sw.Write("<Worksheet ss:Name=\"Sheet1\">\r\n<Table>\r\n<Row><Cell><Data ss:Type=\"String\"></Data></Cell></Row>\r\n</Table>\r\n</Worksheet>");
return sw.ToString();
}
if (dt.Rows.Count == 0)
sw.Write("<Worksheet ss:Name=\"" + replaceXmlChar(dt.TableName) + "\">\r\n<Table>\r\n<Row><Cell ss:StyleID=\"s62\"><Data ss:Type=\"String\"></Data></Cell></Row>\r\n</Table>\r\n</Worksheet>");
else
{
//write each row data
int sheetCount = index / rowLimit;
int i = 0;
for (i = index; i < dt.Rows.Count && i < cntToProceed+index; i++)
{
if ((i % rowLimit) == 0)
{
//add close tags for previous sheet of the same data table
if (sheetCount!=0)
{
sw.Write("\r\n</Table>\r\n</Worksheet>");
sheetCount = (i / rowLimit);
}
sw.Write("\r\n<Worksheet ss:Name=\"" + replaceXmlChar(dt.TableName) +
(((i / rowLimit) == 0) ? "" : Convert.ToString(i / rowLimit)) + "\">\r\n<Table>");
//write column name row
sw.Write("\r\n<Row>");
foreach (DataColumn dc in dt.Columns)
sw.Write(string.Format("<Cell ss:StyleID=\"s62\"><Data ss:Type=\"String\">{0}</Data></Cell>", replaceXmlChar(dc.ColumnName)));
sw.Write("</Row>");
}
sw.Write("\r\n<Row>");
foreach (DataColumn dc in dt.Columns)
sw.Write(getCell(dc.DataType, dt.Rows[i][dc.ColumnName]));
sw.Write("</Row>");
}
if (i >= dt.Rows.Count)
sw.Write("\r\n</Table>\r\n</Worksheet>");
}
return sw.ToString();
}
public static void ToExcel(DataTable dtInput, string filename, HttpResponse response)
{
response.Clear();
response.AppendHeader("Content-Type", "application/vnd.ms-excel");
response.AppendHeader("Content-disposition", "attachment; filename=" + filename);
response.Write(getWorkbookTemplateHead());
// Record count to process at once.
int cntToProceed = 10000;
for (int i = 0; i < dtInput.Rows.Count; i += cntToProceed)
{
response.Write(getWorksheet(dtInput, i, cntToProceed));
response.Flush();
}
response.Write(getWorkbookTemplateTail());
response.End();
}
It's somewhat dirty code, but I think that you could understand my intention.
|
|
|
|

|
Hi,
is there any chance to export also the gridview layout/format such colors, borders, font style?
muek
|
|
|
|

|
Hi mmuekk.
can you tell me if you could put styles to the excel sheets? and how??
Thank you
|
|
|
|
 |
|
|
General News Suggestion Question Bug Answer Joke Rant Admin
|
Exporting multiple tables in a DataSet to multiple sheets in an Excel file
| Type | Article |
| Licence | CPOL |
| First Posted | 7 Dec 2008 |
| Views | 101,479 |
| Downloads | 3,576 |
| Bookmarked | 79 times |
|
|