Excel File Error After Using SaveAsDialog in C#

Hello,
I have a project where I am trying to use SaveFileDialog. My code runs fine and saves the file to the directory that I choose. The problem is when I try to open the file I receive an error from Excel stating
 “Excel cannot open the file Test_File.xlsx because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file”
 Is there something happening in my code that is corrupting the file during the save process?
I can’t figure out why I am getting this error. Any help will be greatly appreciated.
I am working in VS 2013 Pro. and using C#. Here’s my code:
private
void btnSave_Click(object
sender, EventArgs e)
Stream saveFile;
SaveFileDialog saveFileDialog1 =
new
SaveFileDialog();           
saveFileDialog1.Title = "Save As";          
saveFileDialog1.Filter = "Excel Files (*.xlsx)| *.xlsx";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;           
if (saveFileDialog1.ShowDialog() ==
DialogResult.OK)
if ((saveFile = saveFileDialog1.OpenFile()) !=
null)
// Code to write the stream goes here.
saveFile.Close();
Thank you,
Dave
David Young

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using ClosedXML.Excel;
using DocumentFormat.OpenXml;
using System.IO;
namespace LoanOrig_FDIC_Codes
public partial class Form1 : Form
SqlCommand sqlCmd;
SqlDataAdapter sqlDA;
DataSet sqlDS;
DataTable sqlDT;
SqlCommand sqlCmdCnt;
public Form1()
InitializeComponent();
//BEGIN BUTTON LOAD CLICK EVENT
private void btnLoad_Click(object sender, EventArgs e)
string sqlCon = "Data Source=FS-03246; Initial Catalog=ExtractGenerator; User ID=MyID; Password=MyPW";
//Set the 2 dateTimePickers to today's date
DateTime @endDate = End_dateTimePicker.Value.Date;
DateTime @startDate = Start_dateTimePicker.Value.Date;
//Validate the values of the 2 dateTimePickers
if (endDate < startDate)
MessageBox.Show("End Date must be greater than or equal to the Start Date OR Start Date must be less than or equal to the End Date ", "Incorrect Date Selection",MessageBoxButtons.OK,MessageBoxIcon.Error);
//Reset both dateTimePickers to todays date
Start_dateTimePicker.Value = DateTime.Today;
End_dateTimePicker.Value = DateTime.Today;
return;
//End of date validation
string sqlData = @"SELECT AcctNbr,
CurrAcctStatCD,
Org,
MJAcctTypCD,
MIAcctTypCD,
NoteOriginalBalance,
ContractDate,
FDICCATCD,
FDICCATDESC,
PropType,
PropTypeDesc
FROM I_Loans
WHERE CAST(ContractDate AS datetime) BETWEEN @startdate AND @enddate ORDER BY ContractDate";
SqlConnection connection = new SqlConnection(sqlCon);
SqlCommand sqlCmd = new SqlCommand(sqlData, connection);
sqlCmd.Parameters.AddWithValue("@startDate", startDate);
sqlCmd.Parameters.AddWithValue("@endDate", endDate);
sqlDS = new DataSet();
sqlDA = new SqlDataAdapter(sqlCmd); //SqlAdapter acts as a bridge between the DataSet and SQL Server for retrieving the data
connection.Open();
sqlDA.SelectCommand = sqlCmd; //SqlAdapter uses the SelectCommand property to get the SQL statement used to retrieve the records from the table
sqlDA.Fill(sqlDS, "I_Loans"); //SqlAdapter uses the "Fill" method so that the DataSet will match the data in the SQL table
sqlDT = sqlDS.Tables["I_Loans"];
//Code section to get record count
sqlCmdCnt = connection.CreateCommand();
sqlCmdCnt.CommandText = "SELECT COUNT(AcctNbr) AS myCnt FROM I_Loans WHERE ContractDate BETWEEN @startDate AND @endDate";
sqlCmdCnt.Parameters.AddWithValue("@startDate", startDate);
sqlCmdCnt.Parameters.AddWithValue("@endDate", endDate);
int recCnt = (int)sqlCmdCnt.ExecuteScalar();
txtRecCnt.Text = recCnt.ToString();
btnExport.Enabled = true;
btnSave.Enabled = true;
//End of code section for record count
connection.Close();
dataGridView1.DataSource = sqlDS.Tables["I_Loans"];
dataGridView1.ReadOnly = true;
//Reset both dateTimePickers to todays date
Start_dateTimePicker.Value = DateTime.Today;
End_dateTimePicker.Value = DateTime.Today;
//END BUTTON LOAD CLICK EVENT
//BEGIN BUTTON EXPORT CLICK EVENT
private void btnExport_Click(object sender, EventArgs e)
{ //ClosedXML code to export datagrid result set to Excel
string dirInfo = Path.GetPathRoot(@"\\FS-03250\users\dyoung\LoanOrig_FDIC_Codes");
if (Directory.Exists(dirInfo))
var wb = new XLWorkbook();
var ws = wb.Worksheets.Add(sqlDT);
ws.Tables.First().ShowAutoFilter = false;
wb.SaveAs(@"\\FS-03250\users\dyoung\LoanOrig_FDIC_Codes\LoanOrig_FDIC_Codes_" + DateTime.Now.ToString("yyyy-MM-dd") + ".xlsx");
MessageBox.Show("File has been exported to U:\\LoanOrig_FDIC_Codes", "File Exported", MessageBoxButtons.OK, MessageBoxIcon.Information);
//End of ClosedXML code
else
MessageBox.Show("Drive " + "U:\\Visual Studio Projects\\LoanOrig_FDIC_Codes" + " " + "not found, not accessible, or you may have invalid permissions");
return;
//END BUTTON EXPORT CLICK EVENT
private void Form1_Load(object sender, EventArgs e)
//Set dates to be today's date when the form is openend
Start_dateTimePicker.Value = DateTime.Today;
End_dateTimePicker.Value = DateTime.Today;
private void Form1_Load_1(object sender, EventArgs e)
// TODO: This line of code loads data into the 'dataSet1.I_Loans' table. You can move, or remove it, as needed.
this.i_LoansTableAdapter.Fill(this.dataSet1.I_Loans);
private void iLoansBindingSource_CurrentChanged(object sender, EventArgs e)
//BEGIN THE SAVE AS PROCESS
private void btnSave_Click_1(object sender, EventArgs e)
Stream saveFile;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Title = "Save As";
saveFileDialog1.Filter = "Excel Files (*.xlsx)| *.xlsx";
saveFileDialog1.FilterIndex = 1;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
if ((saveFile = saveFileDialog1.OpenFile()) != null)
// Code to write the stream goes here.
saveFile.Close();
private void btnExit_Click(object sender, EventArgs e)
this.Close();
//END THE SAVE AS PROCESS
Here is the code for the whole project up to this point
David Young

Similar Messages

  • Excel file error after upgrade from 2010 to 2013

    Hi there,
    I did the upgrade from 2010 (Enterprise) to 2013. The excel files are not opening giving error.
    ULS Log: "Unexpected error when trying to access service settings in the configuration database. Make sure the proxy for this service application is a member of the default proxy group for the active web application. Error = ExcelServerWebServiceApplication.Local:
    Could not get the web application associated with this context. This indicates that the Excel Server service is not properly registered or provisioned.."
    Question : Do I need to create New Excel Service Application separately on SharePoint 2013 Server?
    I followed this link for upgrade
    http://technet.microsoft.com/en-us/library/jj839719.aspx but it doesn't say anything for Excel SA.
    Note: I have plan to configure separate Office APP Server to give user access the documents on iPad/iPhone. Should I need to do any configuration related to this error on Office App Server?
    Please advice.
    Thanks,
    Khushi

    Hi Khushi ,
    Yes, you need to create New Excel Service Application separately on SharePoint 2013 Server. Due to  only the following service applications have databases that can be upgraded when you upgrade from SharePoint
    Server 2010 to SharePoint Server 2013:
    Business Data Connectivity service application
    Managed Metadata service application
    PerformancePoint Services service application
    Search service application
    Secure Store Service application
    User Profile service application
    Attaching and upgrading these databases configures these service applications. Settings for other services will have to be reconfigured when you upgrade.
    Reference:
    Services upgrade overview for SharePoint Server 2013
    For configuring Office Web Apps Server , you can refer to the blog:
    http://stevegoodyear.wordpress.com/sharepoint-2013-build-guide/office-web-apps-2013-server-install-and-configuration/
    Best Regards,
    Eric
    Eric Tao
    TechNet Community Support

  • How to upload Excel file in BI using function module in abap program

    How to upload Excel file in BI using function module in abap program?

    Hi Anuj,
    To upload the file , you can try a standard program "RSEPSFTP" .
    while you execute the program , a selection screen appears in which the inputs should be give as
    RFC destination - The target server name
    FTP command- PUT
    local file - your file name
    local directory - path of your local file
    remote file - your target file name
    remote directory - where it has to be stored
    Hope this is useful for you
    Thanks & regards
    Anju

  • Sim card error after using pandora

    I'm getting frequent 'sim not installed' errors after using Pandora app. Anybody else having an issue like that??

    I agree...start with the SIM card first...if that doesn't fix it then pop into the closest Apple Store...

  • How to generate excel file as output using OWB

    Hi,
    I have a requirement to generate an excel file as output using OWB.
    I am trying for a direct approach to create excel files.
    Though I know that excel can be created from a .csv file, I am looking for a direct approach to generate excel file without involving any .csv to excel conversion externally.
    Regards,
    Sri

    so, we are trying to do it by the help of oracle heterogeneous services. In my opinion it is possible (it depends on feature of ODCB Excel driver)
    For more details look at thread (it is about MS SQL Server but maybe it helps)
    Oracle to SQL SERVER
    Regards,
    Oleg

  • Using Lab view ver 6,How can I read a cell of excel file right after I write to it

    How can I read a specif cell of an Excel file using Labview VI.

    Hi,
    Attached is a LV6.1 VI which will read a cell.
    It will be looking for a sub VI found in the example C:\Program Files\National Instruments\LabVIEW\examples\comm\ExcelExamples.ll​b.
    The returned value is a string value but there is no reason why it couldn't be a number. Just connect a numeric to the type connector of the Variant to Data function.
    Hope this helps.
    Regards
    Ray Farmer
    Regards
    Ray Farmer
    Attachments:
    Get_Cell_Value.vi ‏41 KB
    Write_Table_To_XL.vi ‏101 KB

  • Excel generated errors after completion of VI

    Hello everybody..
    I created a VI that using activeX it opens an excel file from desktop, renames the worksheet "sheet1", and closing as well as saving the changes. It works ok, then  i open the excel file to see the changes , and when i close it it gives an error message "excel has created errors and will be closed bywindows" etc,etc.
    I guess it's something to do with the order i close the automation references, but after a lot of tries no luck...
    I am using LV7.1 and MS office excel 2000.
    If anyone can help me please do...
    Thanx a lot for your time guys...
    Yiannis
    I attach the vi if anyone wants to try it out!!
    Attachments:
    problem.vi ‏64 KB

    Hi all. I have almost the same problem again, but now I can’t
    tackle it for the moment.
    I created this vi which is part of another vi, and it does
    this:
    It creates a new excel at the first run, name it month.xls (June,
    July etc.) and it renames the worksheet according to the date e.g. 25 June
    2008. It closes all refnums and applications. Then in 20 seconds (for debug
    reasons) it checks the date. If the PC clock is set to another date it checks
    the month if it’s the same it adds another worksheet to the previous excel, if
    its another month it creates a new excel and so on. If anyone wants to run it
    he has to change the date in this 20 seconds that the loop waits.
    Problem: Excel stays in memory and you have to kill it from
    Task manager to open the created excel. I can’t see the problem since I close
    all references and quit the application at the end. I post this question if
    anyone wishes to help. Thank you very much in advance guys.
    PS. LV7.1 MS Excel 2000 (with service packs).
    Cheers
    Yiannis
    Attachments:
    excelmemoryprob.vi ‏123 KB

  • Excel macro error after deploying in Weblogic

    Halo,
    I have written excel macros and it is working fine.
    but if the same file if i try to open from hyperlink after deploying in Weblogic server , I get the error
    "error occured initializing the VBA libraries.
    If Microsoft Visual Basic for Applications (VBA) was not installed, or was set to Install on first use,
    (advertised, or set to install on demand) you may receive this error message.
    Depending on the mode of installation used and the rights of the user to change current settings,
    it is possible to install VBA through Control Panel, Add/Remove Programs, Microsoft Office, Add or Remove
    features. If Visual Basic for Applications is not listed as an installable feature of Office, the administrator
    of your system may have disabled it so it is impossible for you to install it. If VBA is not installed,
    it is impossible to run VBA applications/projects on this computer. "
    1. Even though Excel VBA application is installed in my machine , why am i getting this error.??
    2. I would like to know is there any way to open the excel file even though if the excel software is not installed in client machine??
    Appreciate your help.
    Thanks.

    Hi,
    I do not see any reason for this to not work.
    Is there any difference between the preferences for RX and RXI. Please go to "edit" -> "Preferences" -> "Security(Enhanced)" and uncheck "Enable protected mode at startup".
    Are you able to open any pdf from command line with the same command:
    "C:\Program Files (x86)\Adobe\Reader 11.0\Reader\AcroRd32.exe"  <<PDF_FILE>>
    Thanks,
    Amish.

  • Modifying and saving a Excel file by the use of Blob-Stream Method?

    Hi everyone...
    I'm trying to change and modify a Excel file which is received as Blob variable from database.
    I wrote a PL/SQL Procedure which get the Excel file and convert it to blob; after that send it as the parameter of a Java source called TestPrintExcel
    CREATE OR REPLACE DIRECTORY VMI_TEST_DIR AS '/afc/opt/dba/test_utl_dir';
    GRANT READ, WRITE ON DIRECTORY SYS.VMI_TEST_DIR TO SYSTEM;
    declare 
       bfi  bfile := bfilename('VMI_TEST_DIR','TestFzglist.xls');
       bin  blob;
       cout clob;  
    begin
       dbms_lob.open(bfi);
       dbms_lob.createtemporary(bin, true);
       dbms_lob.loadfromfile(bin, bfi, dbms_lob.getlength(bfi));
       dbms_lob.close(bfi);
       dbms_lob.createtemporary(cout, true);
       dbms_java.set_output(100000);
       TestPrintExcel(bin);
       dbms_output.put_line('done!');
    end;With the following Java procedure I can read the content of the Excel file and write it to database perfectly. But the question is, how can i save the excel file with the same way, if i would change or insert any cell? I mean with the same way that to save as blob stream. Because i get permission error when i use another methods like FileOutputStream, FileInputStream etc. That's way i want to resolve this problem with the blob-stream method. Can anybody tell me how i can do that or what a method i have to use?
    Thanks.
    create or replace and compile java source named xltest as
      import org.apache.poi.ss.usermodel.WorkbookFactory;
      import org.apache.poi.ss.usermodel.Workbook;
      import org.apache.poi.ss.usermodel.Sheet;
      import org.apache.poi.ss.usermodel.Row;
      import org.apache.poi.ss.usermodel.Cell;
      import org.apache.poi.ss.util.CellReference;
      import org.apache.poi.ss.usermodel.DataFormatter;
      import org.apache.poi.ss.usermodel.FormulaEvaluator;
      import java.util.*;
      import java.sql.*;
      import oracle.sql.*;
      import oracle.jdbc.driver.*;
      public class XLTEST {
        public static void printx( oracle.sql.BLOB xblin ) throws SQLException {                       
          Connection Conn = null;
          try {
            Conn = DriverManager.getConnection( "jdbc:default:connection:" );
            Workbook wb = WorkbookFactory.create( xblin.getBinaryStream() ); // "/afc/opt/dba/test_utl_dir/TstFzglist.xls"
            for ( int sheetNum = 0; sheetNum < wb.getNumberOfSheets(); sheetNum++ ) {  //NumberOfSheets
              String TableName = new String();       
              switch( sheetNum )
                case 0:
                  TableName = "freeimportxls_s1"; break;           
                case 1:
                  TableName = "FreeImportXLS_S2"; break;
                case 2:
                  TableName = "FreeImportXLS_S3"; break;
                default:
                  break;                  
              Sheet sheet1 = wb.getSheetAt(sheetNum);         
              java.util.Iterator<Row> ri = sheet1.rowIterator();                 
              while ( ri.hasNext() ) {
                Row row = ri.next();
                java.util.Iterator<Cell> ci = row.cellIterator();                       
                while ( ci.hasNext() ) {
                  Cell cell = ci.next();
                  CellReference cellRef = new CellReference( row.getRowNum(), cell.getColumnIndex() );                         
                  switch( cell.getCellType() ) {
                  case Cell.CELL_TYPE_STRING:                            
                    Values   += "'" + cell.getRichStringCellValue().getString() + "'";               
                    break;
                  case Cell.CELL_TYPE_NUMERIC:
                    Values   += "'" + cell.getNumericCellValue() + "'";
                    break;
                  case Cell.CELL_TYPE_BOOLEAN:
                    Values   += "'" + cell.getBooleanCellValue() + "'";
                    break;
                  case Cell.CELL_TYPE_FORMULA:
                    Values   += "'" + cell.getCellFormula() + "'";
                    break;
                  default:
                    Values   += "''";               
                  int Counter1 = cell.getColumnIndex() + 1;
                  int Counter2 = row.getLastCellNum();
                  if ( Counter1==Counter2 ) {
                    Values   += ")";                          
                  else {
                    Values   += "," ;
                } System.out.println ( Values );               
                if ( ( sheetNum >= 0 ) && ( sheetNum <=2 ) ) {
                   String sqlUpdate = "INSERT INTO " + TableName + " VALUES " + Values;
                   PreparedStatement pstmt = Conn.prepareStatement( sqlUpdate );                                          
                   pstmt.executeUpdate();           
                   pstmt.close();              
            } Conn.close();
          } catch ( java.sql.SQLException e ) {       
            System.err.println( e.getMessage() );
            e.printStackTrace( System.err );
            Conn.close();}        
      };

    Hi,
    Because i get permission error when i use another methods like FileOutputStream, FileInputStream etc.Permission errors are generally resolved by granting the proper privilege via DBMS_JAVA.grant_permission procedure.
    Have you already tried that?
    http://download.oracle.com/docs/cd/E11882_01/java.112/e10588/chten.htm#BABHDBCJ

  • Upload Excel File to SharePoint using VBA

    Hi,
    I copied and modified the code from a friend which he got it from this website forum.
    This apprantely works for some people and not me. Please tell me what I am doing wrong.
    Ignore xxxxxx part of the Sharepoint site. Nothing wrong with the site, i tried many combinations, but I get not response, not even an error.
    Public Const HR_URL = "http://sun.xxxxxx.com/eng/st/Lists/Database%20Change% 20Request"
    Sub test()
    'Upload new Excel sheet to SharePoint
    Call copyToSharePoint(HR_URL, ThisWorkbook.FullName)
    End Sub
    '''''''code block from Forum
    Public Sub copyToSharePoint(sharepointURL As String, filePath As String)
    'On Error GoTo errhandler
    'sharePointUrl should not end in a "/"
    'Initialize Variables
    Dim LlFileLength As Long
    Dim Lvarbin() As Byte
    Dim LobjXML As Object
    Dim LvarBinData As Variant
    Dim LstrFileName As String, PstrFullfileName As String, PstrTargetURL As String
    Dim fileName As String, lenFileName As Long
    'Extract file name
    lenFileName = Len(filePath) - InStrRev(filePath, "\")
    fileName = Right(filePath, lenFileName)
    'Check that the webUrl ends in an "/"
    If Right(sharepointURL, 1) <> "/" Then
    sharepointURL = sharepointURL & "/"
    End If
    '**************************** Upload binary files *****************
    Set LobjXML = CreateObject("Microsoft.XMLHTTP")
    PstrFullfileName = filePath
    LlFileLength = FileLen(PstrFullfileName) - 1
    ' Read the file into a byte array.
    ReDim Lvarbin(LlFileLength)
    Open PstrFullfileName For Binary As #1
    Get #1, , Lvarbin
    Close #1
    ' Convert to variant to PUT.
    LvarBinData = Lvarbin
    PstrTargetURL = sharepointURL & fileName
    ' Put the data to the server; false means synchronous.
    LobjXML.Open "PUT", PstrTargetURL, False
    ' Send the file in.
    LobjXML.Send LvarBinData
    Set LobjXML = Nothing
    Exit Sub
    errhandler:
    If Err.Number = 53 Then
    MsgBox "Excel was unable to create the HR file to submit to SharePoint. " & vbNewLine & _
    "Please check that you are not running out of disk space and that no MS Office add-in is causing issues with Excel.", vbCritical, "File Error"
    Exit Sub
    Else
    MsgBox "Your HR could not be submitted to SharePoint. The following error occurred:" & vbNewLine & _
    "Error " & Err.Number & ": " & Err.Description, vbCritical, "Error Uploading to SharePoint"
    Exit Sub
    End If
    End Sub

    I have made the following code work successfully on a Windows 8 machine with the VBA executing from an Excel 2010 file and the file you want to upload going to a SharePoint 2010 site. If you don't need to use SP content types then simply
    take that out of the code. Also, pay attention to the FieldInformation as the Field Display names and Field Internal names can sometimes be different. Cheers.
    Public Sub copyDocToSP()
    Const strLocalFile = "C:\temp\myLocalFile.pdf"
    Const spBASE_URL = "https://thesharepointdomian/sites/yoursite/"
    Const spDOC_LIB = "Your SP Doc Library Name"
    Const spFILE_NAME = "FileNameOnceOnSharepoint.pdf"
    Const spCONTENT_TYPE = "0x000000000000000000000000000000000000000"
    Set ObjectStream = CreateObject("ADODB.Stream")
    Set ObjectDOM = CreateObject("Microsoft.XMLDOM")
    Set ObjectElement = ObjectDOM.createElement("TMP")
    Set ObjectHTTP = CreateObject("Microsoft.XMLHTTP")
    'Reading binary file
    ObjectStream.Open
    ObjectStream.Type = 1 'Type Binary
    ObjectStream.LoadFromFile (strLocalFile)
    BinaryFile = ObjectStream.Read()
    ObjectStream.Close
    'Conversion Base64
    ObjectElement.DataType = "bin.base64" 'Type Base64
    ObjectElement.nodeTypedValue = BinaryFile
    EncodedFile = ObjectElement.Text
    'Build request to load document
    strURLService = spBASE_URL + "_vti_bin/copy.asmx"
    strSOAPAction = "http://schemas.microsoft.com/sharepoint/soap/CopyIntoItems"
    strSOAPCommand = "<?xml version='1.0' encoding='utf-8'?>" & _
    "<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>" & _
    "<soap:Body>" & _
    "<CopyIntoItems xmlns='http://schemas.microsoft.com/sharepoint/soap/'>" & _
    "<SourceUrl>" + strLocalFile + "</SourceUrl>" & _
    "<DestinationUrls>" & _
    "<string>" + spBASE_URL + spDOC_LIB + "/" + spFILE_NAME + "</string>" & _
    "</DestinationUrls>" & _
    "<Fields>" & _
    "<FieldInformation Type='Text' InternalName='Title' DisplayName='Title' Value='this is the title value' />" & _
    "<FieldInformation Type='Choice' InternalName='Our_x0020_Status' DisplayName='Our Document Status' Value='Ready-to-distribute' />" & _
    "<FieldInformation Type='Text' InternalName='ContentTypeId' DisplayName='Content Type ID' Value='" + spCONTENT_TYPE + "' />" & _
    "</Fields>" & _
    "<Stream>" + EncodedFile + "</Stream>" & _
    "</CopyIntoItems>" & _
    "</soap:Body>" & _
    "</soap:Envelope>"
    ObjectHTTP.Open "Get", strURLService, False
    ObjectHTTP.SetRequestHeader "Content-Type", "text/xml; charset=utf-8"
    ObjectHTTP.SetRequestHeader "SOAPAction", strSOAPAction
    ObjectHTTP.Send strSOAPCommand
    MsgBox (ObjectHTTP.responseText)
    End Sub

  • Excel type error while using in SSIS 2005

    Hi I am trying to dump the data into excel from OLEDB source.
    However, I want to load it into excel 2007 (.XLSX type) there it is giving below error while creating excel connection manager (destination) 
    (it is working fine for .XLS type but i want to load into 2007 workbook)
    Error desc:
    File path contains invalid Excel file. Please provide file with .xls extension.
    Any idea?
    Thanks

    it will work fine so long as you've installed Access Redistributable
    http://www.microsoft.com/en-in/download/details.aspx?id=13255
    You need to use OLEDB Connection Manager instead of excel Connection Manager for this
    see an example here
    http://www.bidn.com/blogs/devinknight/ssis/504/using-excel-2007-in-ssis-2005
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • Opening an Excel file already created - using ADF faces

    I have an action that exports a bunch of data to an excel file using jXLS, which seems to work nicely. However, the file is exported outside of my application context. I would like to open the file right into the file stream so that when they click on the link, it just opens the file directly in the browser or prompts for download.
    Here's my action code. Any suggestions would greatly appreciated.
         public String selectForExcel() throws IOException {
         final String templateFileName = "../server/default/tmp/stats_template.xls";
         final String destFileName = "../server/default/tmp/chart_output.xls";
         Map beans = new HashMap();
    beans.put("platformStats", deviceStats);
    XLSTransformer transformer = new XLSTransformer();
    transformer.transformXLS(templateFileName, beans, destFileName);
    return "success";
         }

    Add the following code to an action that returns null. The action will return the user to the current page and will be presented with a download prompt. This code should work well for your case.
    Regards.
    public static synchronized void downloadFile(String filename, String fileLocation, String mimeType,
    FacesContext facesContext) {
    ExternalContext context = facesContext.getExternalContext();
    String path = context.getInitParameter("externalFiles") + fileLocation;
    String fullFileName = path + filename;
    File file = new File(fullFileName);
    HttpServletResponse response = (HttpServletResponse) context.getResponse();
    response.setHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
    response.setContentLength((int) file.length());
    response.setContentType(mimeType);
    try {
    FileInputStream in = new FileInputStream(file);
    OutputStream out = response.getOutputStream();
    // Copy the contents of the file to the output stream
    byte[] buf = new byte[1024];
    int count;
    while ((count = in.read(buf)) >= 0) {
    out.write(buf, 0, count);
    in.close();
    out.flush();
    out.close();
    facesContext.responseComplete();
    } catch (IOException ex) {
    System.out.println("Error in downloadFile: " + ex.getMessage());
    ex.printStackTrace();
    }

  • Import Excel file into SQL, using bulk copy - date issues

    Hello. I have a VB project where I need to import multiple excel files with lots of rows and columns into SQL 2012. Currently the import is set up, using OleDbConnection and insert commands and it takes up to 10 minutes to process all the spreadsheets.
    I'm trying to switch the code to use SQLBulkCopy, but experienced issues with dates columns. Some rows have Null dates and those are interpreted as strings and won't import into SQL tables. Is there a way to format the column prior to import programmatically?
    Any advice is appreciated.
    Note -
    If I add column mapping and exclude all dates columns - import works fine. All excel files have date fields, excel files are reports from other vendor and change on weekly bases, manual formatting of the excel files prior to import are out of the question...
    The code is just basic:
    Public Sub ImportFormExcelSample()
    Dim ExcelConnection As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\MyExcelSpreadsheet.xlsx;Extended Properties=""Excel 12.0 Xml;HDR=Yes""")
    ExcelConnection.Open()
    Dim expr As String = "SELECT * FROM [Sheet1$]"
    Dim objCmdSelect As OleDbCommand = New OleDbCommand(expr, ExcelConnection)
    Dim objDR As OleDbDataReader
    Dim SQLconn As New SqlConnection()
    Dim ConnString As String = "Data Source=MMSQL1;Initial Catalog=DbName; User Id=UserName; Password=password;"
    SQLconn.ConnectionString = ConnString
    SQLconn.Open()
    Using bulkCopy As SqlBulkCopy = New SqlBulkCopy(SQLconn)
    bulkCopy.DestinationTableName = "TableToWriteToInSQLSERVER"
    Try
    objDR = objCmdSelect.ExecuteReader
    bulkCopy.WriteToServer(objDR)
    objDR.Close()
    SQLconn.Close()
    Catch ex As Exception
    MsgBox(ex.ToString)
    End Try
    End Using
    End Sub
    The error I get is System.InvalidOperatiomException: The given value of type String from the data source cannot be converted to type date of the specified target column. System.FormatException: Failed to convert parameter value from String to a DateTime...
    Thank you!
    Alla Sanders

    Hi Alla,
    This issue might be caused because the field contains a NULL value, but the date/time columns in your table does not allow NULL values. Furthermore, please aslo take a look at "Data Type Issues" session in the article below:
    http://odetocode.com/blogs/scott/archive/2013/02/08/working-with-sqlbulkcopy.aspx
    Here is a similar thread about this topic for your reference, please see:
    http://social.technet.microsoft.com/Forums/sqlserver/en-US/2d99181c-fc2b-4caf-9530-3bd6ae1745f1/sqlbulkcopy-column-validation-not-working?forum=sqldataaccess
    If you have any feedback on our support, please click
    here.
    Regards,
    Elvis Long
    TechNet Community Support

  • Invalid Zip file error after downloading Solaris 8

    Every time i download the solaris 8 binaries i keep getting the error "Cannot open file - It does not appear to be a valid archive" when trying to unzip the files using winzip 8. Also the files take very long to download as they are 300MB approx... but after all this time it says the files are only a few MB's in size! Can anyone shed some light as to what is happening here???
    Thanks

    I was getting a similar, if not the same, problem when I used IE 5.5 to download the file. It used to start extracting then stop about 75% of the way through and dump some error about the archive being corrupt and not being able to open it. After installing Netscape and disabling the download manager application, I was able to download and extrac the zip files with winzip 8 and also winrar without any problems.

  • Excel File gets Locked using OLE2

    Dear all ,
    We are working with 10g forms
    We are trying to load data from Excel file into a form using OLE2 . We are able to load the data from Excel File .
    Here we try to read the first row of the excel file and verify for a title to be present
    if not present we close the file . we have used the OLE2.Release_OBJ
    declare
    application ole2.obj_type;
    workbooks ole2.obj_type;
    workbook ole2.obj_type;
    worksheet ole2.obj_type;
    cell ole2.obj_type;
    args ole2.list_type;
    Check_file text_io.file_type;
    no_file exception;
    PRAGMA exception_INIT (no_file, -302000);
    cell_value varchar2(2000);
    begin
    Lv_F_File_Type := Text_Io.Fopen(:Cb_Input.Ti_v_File_name,'R');
    application:= ole2.create_obj('Excel.Application');
    workbooks := ole2.get_obj_property(application, 'Workbooks');
    args:= ole2.create_arglist;
    ole2.add_arg(args, :Cb_Input.Ti_v_File_name);
    workbook := ole2.invoke_obj(workbooks, 'Open', args);
    ole2.destroy_arglist(args);
    --Open worksheet Sheet1 of that Workbook
    args:= ole2.create_arglist;
    ole2.add_arg(args, 'Sheet1');
    worksheet := ole2.get_obj_property(workbook, 'Worksheets', args);
    ole2.destroy_arglist(args);
    args:= ole2.create_arglist;
    ole2.add_arg(args, Lv_n_rows);-- lv_n_rows value is 1
    ole2.add_arg(args, 1);
    cell:= ole2.get_obj_property(worksheet, 'Cells', args);
    ole2.destroy_arglist(args);
    cell_value :=ole2.get_char_property(cell, 'Value');
    Lv_v_Title:=cell_value;
    if Upper(Lv_v_Title) <> Upper(Lpk_Var.Lv_v_File_Name_Parameter) then
    Lpk_Alert.Lp_Show('File Title Should be '||Lpk_Var.Lv_v_File_Name_Parameter);
    OLE2.RELEASE_OBJ(cell);
    OLE2.INVOKE(workbook ,'Close');
    OLE2.RELEASE_OBJ(worksheet);
    OLE2.RELEASE_OBJ(workbook);
    OLE2.RELEASE_OBJ(workbooks);
    OLE2.INVOKE(application, 'Quit');
    OLE2.RELEASE_OBJ(application);*/
    end if;
    After this we open the excel , and modify and try to save , it just waits ...
    we are forced to close the form. and then only the excel file gets saved...
    we need to modify the file , when the form is running and then upload the data..
    since the objects are closed , we are unable to understand why the excel file is locked till the session
    Can any one help us
    SSR

    Hi,
    Running on Business Object Enterprise XI 3.1 FP1.5.

Maybe you are looking for